When I use Docker, most of the time I start my containers in detached mode, meaning that the container will deploy in the background without any further interaction from myself. However, every once in a while I find myself needing to connect to the container to view log information.
So how do you connect to a detached container that is already running? We’re going to take a look at how to do this with minimal effort.
Let’s assume you have Docker installed and we want to deploy a Debian container. Typically you would accomplish this by executing the following:
docker pull debian:latest
docker run -d debian
In the above, we are using only the basic settings without any networking or port definitions. Those things are out of the scope of this guide.
If you execute the following command you’ll notice that the container is not running:
This is because this particular container will just terminate after it runs. We can connect to it during deployment, but we won’t be able to connect to it in interactive mode if it starts as detached.
If we wish to connect to it in interactive mode at deployment we would run the following instead:
docker run -it debian
So the above command will deploy the container in interactive mode and keep it running until you exit interactive mode, but that isn’t really what we were originally after. We want to connect to a container that is currently detached.
For this, we need an image that doesn’t terminate as soon as it runs. There are many images like this and you can certainly create your own. Off the top of my head, the Couchbase Docker image will run continuously until stopped.
Let’s execute the following:
docker pull couchbase/server:latest
docker run -d couchbase/server
The above commands will run a Couchbase NoSQL database in detached mode. To find the container id, execute the following command:
With the container id in hand, execute the following to connect to it in interactive shell mode:
docker exec -it 6aac37d314b1 bash
At this point you should be controlling the container via your Command Prompt or Terminal. When you exit from interactive mode, this particular container will still be running until we stop it.
Not too bad right? You now have the knowledge to take more control of your Docker containers.
A video version of this article can be seen below.