How to Exit a Docker Container
This quick little docker tip shows how to exit a docker container.
β Abhishek Prakash
How do you exit a docker container?
Suppose you run a docker container in interactive mode like this:
docker run -it ubuntu bash
This way, you get an interactive shell and you are immediately logged into the OS running as container.
To exit from this running container, you can use ctrl+c, ctrl+d or enter exit in the terminal.
There is one problem here. If you exit the container this way, your container stops as well.
abhishek@nuc:~$ docker run -it ubuntu bash
root@1385a55c8c7a:/# ls
bin dev home lib64 mnt proc run srv tmp var
boot etc lib media opt root sbin sys usr
root@1385a55c8c7a:/# exit
exit
abhishek@nuc:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
As you can see on the output above, the docker ps command shows no running containers.
Exit docker container without stopping it (detach container)
What you can do here is to detach the container by pressing ctrl+p and ctrl+q one after another. I know itβs a weird keyboard shortcut for Linux users but thatβs how you can do it easily.
When detached, your container will keep on running even if you exit the container. Your interactive docker session is now in daemon mode.
You can verify it using docker ps
command to see it in the running containers list.
When you want to use it again, you can attach the container again.
Tip: Run container in daemon mode whenever possible
I always prefer to run containers in daemon mode like this:
docker run -it -d docker_image_name bash
This way the container starts and run in the background. The i flag means interactive and t flag stands for tty. So basically, it gives you an interactive shell that runs bash but it is not available immediately.
You can enter a running container in this way:
docker exec -it container_id bash
I hope this quick little docker tip was useful for you. Stay tuned for more docker tips.
If you have any questions or suggestions, please feel free to ask in the comment section.
Creator of Linux Handbook and It's FOSS. An ardent Linux user & open source promoter. Huge fan of classic detective mysteries from Agatha Christie and Sherlock Holmes to Columbo & Ellery Queen.