Exiting a Docker Container

Want to exit a docker container? You have several options to choose from. Here’s a trick you can use, to send a Docker container you have started with an interactive command into the background.

Let’s say you have started the container with something like:

docker run -it busybox sh

The Common Approach, Stopping the Container

If you have started the container interactively, and are in a bash-like environment, you’d usually type ctrl+d to exit the session. If it’s another process running, the combination would be ctrl+c.

This is not what you want in this case. But those cause the command to stop, which in turns stops the container. What if you want it to keep running, but not in the terminal?

The Solution

You can exit an interactive Docker session, without doing the above. What you want to do in that case, is daemonize the container. By doing this, you get what you’d have if you started it with -d in the first place.

By typing ctrl+p and ctrl+q after each other, you turn interactive mode to daemon mode, which keeps the container running but frees up your terminal.

You can attach to it later using docker attach, if you need to interact with the container more.

Of course you should not rely on this workflow for anything more than experimenting around. Don’t rely that important data will be available inside the container, unless it’s in a mounted volume. Your container will not survive a reboot of the host machine - the data will be lost and the container won’t be running.

A Better Workflow

While the above works, here’s an alternative workflow you should consider. Run your container, so it executes the command you’re interested in. Run it directly in the background, by starting it in detached mode with -d.

Once it runs, you can execute other commands in the same container with exec, such as:

docker exec -ti CONTAINER_ID bash

The above will start a bash session in the same container, which is great for taking a look around if you need to and perform one-off maintenance tasks.

Join the mailing list!

Subscribe to get notified about future articles and stay in touch via email.

I write about Kubernetes, Docker, automation- and deployment topics, but would also like to keep you up to date about news around the business-side of things.

Privacy and your data: You can get more information about the usage of your data, the storage of your registration, sending out mails with the US-provider ConvertKit, statistical analysis of emails sent and your possibility to unsubscribe in my Privacy Policy.

I use the US-provider ConvertKit for email automation. By clicking to submit this form, you acknowledge that the information you provide will be transferred to ConvertKit for processing in accordance with their Privacy Policy and Terms.

We won't send you spam. Unsubscribe at any time. Powered by ConvertKit