SSH into a Docker container? Use docker exec instead

Do you want to SSH into a Docker container?

Perhaps you need to have a look around, run commands, or debug something.

Well, most Docker containers don’t run the ssh daemon. So, there’s no SSH service available to service your requests. (Sorry!)

Instead, if you need to be able to get inside the Docker container, you need docker exec.

Getting a terminal inside a Docker container

A Docker container isn’t the same as a virtual machine.

It’s basically a single application which runs inside a very small isolated box.

Containers run many stuff and things. But containers are small and run one single process.

VMs: such things. Containers: so small.

So, if you want to get inside the box, you can’t use SSH, because it doesn’t exist in the container. You have to do something different.

To be able to run commands inside a Docker container when it’s running, use docker exec to start a shell, like sh or bash.

First, you’ll need to get the ID or name of your container using docker ps:

$ docker ps
CONTAINER ID  IMAGE                              ....     NAMES
79f6e55215a6  localhost/node-json-server:latest  ....     sleepy_maxwell

Here I could use the ID (79f6e55215a6) or the name (sleepy_maxwell).

Most containers will have sh installed, so this example should work for most containers:

docker exec -it my-container-ID /bin/sh

Now you’ll get a terminal and you can do as you like.

Whenever you want to exit, just press Ctrl+C. The container will keep running.

Some super-lightweight images don’t even include a shell by default. So if sh and bash don’t exist, then check with whoever has provided your image.

How to remember the command

Keep forgetting the command? I find this mnemonic handy:

  • Docker

  • I want to execute something in the container

  • So give me an Interactive Terminal.

  • in (the container name)

  • And be quiet about it (shhhh!)

Which is…

docker exec -it <container-ID> /bin/sh

If you really do need SSH

If you have a use case where you really do need to run an SSH service inside your container, then:

  1. Find an existing Docker image to use as a base in a Dockerfile

  2. Extend the image by installing packages for SSH, and running an SSH daemon.

If you’re not sure whether you need SSH, then you should lean towards not having it.

It’s an additional security risk, it means you need to manage keys, and you should avoid going into a container to make edits or changes.

If you want SSH because you want to make changes to your app, stop the container, and start a new one, with the updated configuration. (Docker containers are considered to be disposable or throw-away.)

Comments

Got any thoughts on what you've just read? Anything wrong, or no longer correct? Sign in with your GitHub account to leave a comment.

(All comments get added as Issues in our GitHub repo here, using the comments tool Utterances)