Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to detach from a container without stopping it

Tags:

docker

In Docker 1.1.2 (latest), what's the correct way to detach from a container without stopping it?

So for example, if I try:

  • docker run -i -t foo /bin/bash or
  • docker attach foo (for already running container)

both of which get me to a terminal in the container, how do I exit the container's terminal without stopping it?

exit and CTR+C both stop the container.

like image 319
mtmacdonald Avatar asked Aug 12 '14 14:08

mtmacdonald


People also ask

Can we remove a container before stopping it?

Removing Docker ContainersDocker containers are not automatically removed when you stop them unless you start the container using the --rm flag.

How do you get out of a container?

Just Stopping the Container If you want to stop and exit the container, and are in an interactive, responsive shell - press ctrl+d to exit the session. You could as well type the exit command. TL;DR: press ctrl+c then ctrl+d - that means, keep the ctrl key pressed, type a c, and let go of ctrl.

How do I detach from docker compose?

Starting and Stopping Docker Compose You can stop it using CTRL+C (run once for the preferable graceful shutdown, or twice to force-kill). You can start Docker Compose in the background using the command docker-compose up -d . If using this method, you'll need to run docker-compose stop to shut it down.


2 Answers

Type Ctrl+p then Ctrl+q. It will help you to turn interactive mode to daemon mode.

See https://docs.docker.com/engine/reference/commandline/cli/#default-key-sequence-to-detach-from-containers:

Once attached to a container, users detach from it and leave it running using the using CTRL-p CTRL-q key sequence. This detach key sequence is customizable using the detachKeys property. [...]

like image 76
Larry Cai Avatar answered Oct 05 '22 00:10

Larry Cai


Update: As mentioned in below answers Ctrl+p, Ctrl+q will now turn interactive mode into daemon mode.


Well Ctrl+C (or Ctrl+\) should detach you from the container but it will kill the container because your main process is a bash.

A little lesson about docker. The container is not a real full functional OS. When you run a container the process you launch take the PID 1 and assume init power. So when that process is terminated the daemon stop the container until a new process is launched (via docker start) (More explanation on the matter http://phusion.github.io/baseimage-docker/#intro)

If you want a container that run in detached mode all the time, i suggest you use

docker run -d foo 

With an ssh server on the container. (easiest way is to follow the dockerizing openssh tutorial https://docs.docker.com/engine/examples/running_ssh_service/)

Or you can just relaunch your container via

docker start foo 

(it will be detached by default)

like image 22
Regan Avatar answered Oct 04 '22 23:10

Regan