How to Exit a Docker Container

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.

Stop Docker Container: Single, Multiple or All of Them
This docker tutorial discusses methods to stop a single docker container, multiple docker containers or all running docker containers at once. You’ll also learn to gracefully stop a docker container.

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.