Quickly SSH into a Docker container

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.

Problem

Basically the routine is to run docker ps:

If you scroll to the right of that you’ll see the randomly generated port in the PORTS column:

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!

Solution

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 "e53a722096f0" or "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.

Closing

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.

5 thoughts on “Quickly SSH into a Docker container

  1. Bart M

    There’s no real need to forward port 22 if you only need access from the docker host, you can just ssh like this:

    ssh root@$(docker inspect | grep IPAddr | sed -e ‘s/.*: “\(.*\)”.*/\1/’)

    I actually added this to my .bashrc on my docker host:

    function docker_ssh() { ssh root@$(docker inspect $1 | grep IPAddr | sed -e ‘s/.*: “\(.*\)”.*/\1/’); }

    then you can just do “docker_ssh “

Comments are closed.