I’ve been playing around with Docker for a few months and it’s great.
One thing that is slightly rage-inducing when using docker is having to SSH into a container. Generally if you have multiple containers that run
sshd, you’ll want the SSH ports to be generated randomly to prevent conflicts. Connecting via SSH is slightly tedious to do in this case, as there are several steps involved.
Please note that this article is quite old. Docker has this functionality inbuilt now. This will do the trick:"docker exec -it [container id]"
I’ve left the blog post here for historic reasons.
Basically the routine is to run
If you scroll to the right of that you’ll see the randomly generated port in the
The next step is to type out the SSH command. You can either give in to RSI by copying the port with the mouse, or type it out:
I think that’s too much work to simply SSH into a container!
I gave into annoyance and wrote a straightforward Python script to automatically do this for me. The Python script is called
dssh. It runs
docker inspect, grabs the port, then runs SSH for you:
You might notice it makes some assumptions which will crash the script if they’re not followed. There needs to be an argument for the container ID or name. In the example above I could use either
"es-b" as the argument. There also has to be an
sshd process port listening on 22, and a configured container to forward that port.
The output of
docker inspect is a handy JSON string coming straight from the Docker Remote API. This in turn gives us the port we need. We then simply run
subprocess.call and suddenly you’re in the container.
I did attempt this not long ago but failed. The attempt was to use docker-py but unfortunately it seemed to need root, which I couldn’t work a way to avoid it. I needed to SSH into docker as my non-privileged user because of SSH keys, so instead I made it print out the SSH command for it to be executed, but it was a cumbersome solution.
If you want the latest version, it’ll be updated in my dotfiles repository on github.