Docker - How To SSH Into A Container

Docker is an open platform for developing, shipping, and running applications aimed at delivering applications faster. It allows you to separate your applications from your infrastructure and treat your infrastructure like a managed application thereby helping you to ship code faster, test faster, deploy faster, and shorten the cycle between writing code and running code.

A container consists of an operating system, user-added files, and meta-data. Each container is built from an image which tells Docker what the container holds, what process to run when the container is launched, and a variety of other configuration data. Each container should be responsible for one and only one process. For instance, if you have PHP and Apache, each should have its own separate container, and as soon as the process ends, the container stops.

While working with Docker however, it may be necessary to execute a command inside the container or to even "ssh" into the container. This should generally be seen as bad practice when you have your infrastructure set up properly, however during the initial setup phase it might make your life easier to see and control what's happening inside on-the-fly.

The first thing you need to do is find out the actual name of your container. You can do this with the docker ps command, which is named after the standard Linux command, ps. Here's how to do it:

[email protected]:~# docker ps
CONTAINER ID        IMAGE                           COMMAND             CREATED             STATUS              PORTS               NAMES
b8755f65eaed        vendor/container_name:latest    "/start.sh"         8 weeks ago         Up 8 weeks          80/tcp              container_name_1

Here you'll should see the ID of your container, the name of the image, the entry-point, some info about the uptime of the container, and finally the name. Now, using that name, we can execute commands in the container. For example:

[email protected]:~# docker exec -it container_name_1 supervisorctl status

In that same way we can "ssh" to the container. We aren't really using SSH to do this, but rather starting a normal shell. Here's how:

[email protected]:~# docker exec -it container_name_1 /bin/bash
[email protected]:/# 

Now you can see what files might be getting generated or modified within the container and you can manually modify your configs and code here. Note that you should not do this on a production server, and don't forget that if you restart the main process of the container (e.g. if it's an Apache container and you restart Apache) you will kill the container.