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?
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.