Introduction
Docker management tasks frequently demand running commands inside containers. Once the user performs the required operation, they must exit the container to resume work in their system's shell session.
This article shows you how to exit a Docker container.
How to Exit Docker Container from an Interactive Shell Session
To access a container shell prompt, use Docker commands such as docker run, docker exec, and docker attach. For example, the following docker run
command runs a container based on the Alpine Linux official image and starts an interactive session inside the container using an sh
shell prompt:
docker run -it alpine sh
Docker starts the container, and the prompt appears.
There are two ways to exit a Docker container interactive shell session. One method exits and stops the container, while the other keeps the container and its processes running in the background.
The sections below provide details for both methods.
Method 1: Exit and Stop Docker Container
Perform the following actions to close the interactive terminal shell and stop the container.
1. If a process is running in the container, press Ctrl+C to send the SIGINT signal and stop the process. The screenshot below shows Ctrl+C interrupting the ping command.
2. Next, press Ctrl+D to exit and stop the container.
Alternatively, type the exit
command to achieve the same effect as when pressing Ctrl+D:
exit
Method 2: Exit Docker Container without Stopping It
If you want to exit the container's interactive shell session, but do not want to interrupt the processes running in it, press Ctrl+P followed by Ctrl+Q. This operation detaches the container and allows you to return to your system's shell.
The example below runs the ping
command in the container, then interrupts the session with Ctrl+P and Ctrl+Q.
The shell session ends, but the container continues to run in the background. Confirm this by listing the running containers with the command below:
docker ps
The container appears on the list.
To return to the container's interactive shell, use docker attach
followed by the name or ID of the container.
docker attach [container-name-or-id]
Once the container attaches, the ping
command output resumes printing in the terminal.
Note: You can also run the container in the detached mode from the start. To do this, add the -d
option to the docker run
command:
docker run -it -d alpine sh
Conclusion
This article presented two methods to exit a Docker container. The first method included stopping the exited container, while the second preserved the running container processes.
Learn more about the basic container operations by reading How to List/Start/Stop Docker Containers.