558

I can attach to a docker process but Ctrl+C doesn't work to detach from it. exit basically halts the process.

What's the recommended workflow to have the process running, occasionally attaching to it to make some changes, and then detaching?

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
MarkL
  • 8,770
  • 7
  • 26
  • 27

18 Answers18

798

To detach the tty without exiting the shell, use the escape sequence Ctrl+P followed by Ctrl+Q. More details here.

Additional info from this source:

  • docker run -t -i → can be detached with ^P^Qand reattached with docker attach
  • docker run -i → cannot be detached with ^P^Q; will disrupt stdin
  • docker run → cannot be detached with ^P^Q; can SIGKILL client; can reattach with docker attach
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Ken Cochrane
  • 75,357
  • 9
  • 52
  • 60
  • this worked fine for me. One possible reason it may not hav eworked for Zenexer is that I think you do not want the -d in the original run command. You also do no need the /bin/bash shell script. After all, you are specifying it is an interactive session and you are allocating a tty. – Ed Ost Sep 21 '14 at 00:11
  • 1
    Actually I tested and the -d does not hurt. It is the /bin/bash command you are giving. You probably have an extra layer of shell involved that you don't need. If you use -d it will return immediately and you can attach to it if you choose. Without the -d you will be in interactive mode. Do you business then ^p^q out. – Ed Ost Sep 21 '14 at 00:18
  • 21
    I found that even when running with -it, the detach sequence fails if you also start the container with the cleanup flag (--rm). This might be obvious to some, but it bites me more often than I would like to admit. – allingeek Nov 12 '14 at 07:43
  • Did not work for me either. The answer below *docker attach -sig-proxy=false 304f5db405ec* works though. – Steven Jan 19 '15 at 20:04
  • 10
    Another option is to just close your terminal window or cmd-w :) – buildmaestro May 06 '16 at 00:05
  • 2
    ^q is is used by default to start (resume) terminal output that is paused by ^s. To use ^q for other purposes (like for docker) you have to unset it. You can do that with `stty start ""` This should fix it for all those people whose ^p^q doesn't work. – Matthew Hannigan Jan 01 '18 at 02:01
  • 8
    You can set configurable detach keys with e.g. `"detachKeys": "ctrl-a,a"` in your .docker/config.json file or `--detach-keys "ctrl-a,a"` on the command line with attach etc. – Matthew Hannigan Jan 01 '18 at 02:31
  • 4
    `Ctrl + Z` doesn't detach; it just backgrounds the process. It's not the same as detaching and carries a performance penalty. – Zenexer Mar 11 '18 at 23:27
  • On Mac . its Ctrl+ Q – raga Apr 28 '18 at 05:13
  • is there any way to detach from inside a bash script? trying to enter and exit a container with a script. – Austin Jun 24 '18 at 23:12
  • 1
    `^P^Q` in English, procedurally: while holding down `Ctrl`, push `P` then push `Q`, then let go of `Ctrl`. – Dmitry Minkovsky Dec 12 '18 at 15:57
  • In git bash terminal inside VS Code, for me it was Ctrl + Z :) wish you luck guys – Vladislav Guleaev Jun 23 '19 at 07:52
  • How to detach when running it from expect script? – Maciek Rek Jul 21 '20 at 11:19
  • This doesn't work on Google Cloud Platform's Compute Engine – Arrow_Raider May 05 '21 at 16:38
  • 1
    Typing Ctrl Q is hard because https://retrocomputing.stackexchange.com/questions/7263/history-of-ctrl-s-and-ctrl-q-for-flow-control, a lot of terminals will intercept it. In GNU screen Ctrl A Ctrl K to kill the "window" (@buildmaestro's suggestion) works. – Terry Brown Dec 15 '21 at 16:20
  • THis works with "docker run -it" but not from "docker run -t" – Brad Jan 23 '22 at 21:56
206

Check out also the --sig-proxy option:

docker attach --sig-proxy=false 304f5db405ec

Then use Ctrl+C to detach

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
czerasz
  • 13,682
  • 9
  • 53
  • 63
  • 4
    To try this starting with run instead of attach, I tried: `docker run -ti --sig-proxy=false busybox top` which seems not to work, the process is killed with ctrl-c but starting with `docker run -t -sig-proxy=false busybox top` seemed to work and enable quitting with ctrl-c – Henning Jul 08 '14 at 13:36
  • 1
    `Ctrl-c` will stop the container also. – Evan Hu Jul 10 '19 at 03:26
  • It is the only solution from the ones listed here which works for me on Debian 9 server running Docker 19.03.5. Question is, why isn't this the default setting for attach commands? It seems to be the most common use case. – fviktor Dec 12 '19 at 06:38
  • The Ctrl-p, Ctrl-q sequence do not work for me (started as docker container attach xyz).. but this does. Thanks @czerasz – PravyNandas Jan 09 '20 at 18:32
113

If you just want to make some modification to files or inspect processes, here's one another solution you probably want.

You could run the following command to execute a new process from the existing container:

sudo docker exec -ti [CONTAINER-ID] bash

will start a new process with bash shell, and you could escape from it by Ctrl+C directly, it won't affect the original process.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Colin Su
  • 4,613
  • 2
  • 19
  • 19
  • 8
    This worked, you can type "exit" once you're done without affecting the original process. – Eko3alpha Oct 11 '16 at 13:27
  • This is a great way to attach to a running container. But what if (say) I have some process running in the container and I want to restart that process? Ah, I can just kill the old process, restart the new one, and use C-p,C-q, which works since it's an interactive tty. I like the --sig-proxy=false method as well, but this is more versatile and doesn't force disruption of the current process. – taranaki Feb 14 '17 at 07:34
  • 2
    "attach" has a specific meaning with Docker, and `exec` is not it. – frnhr May 30 '20 at 16:09
56

To detach from a running container, use ^P^Q (hold Ctrl, press P, press Q, release Ctrl).

There's a catch: this only works if the container was started with both -t and -i.

If you have a running container that was started without one (or both) of these options, and you attach with docker attach, you'll need to find another way to detach. Depending on the options you chose and the program that's running, ^C may work, or it may kill the whole container. You'll have to experiment.

Another catch: Depending on the programs you're using, your terminal, shell, SSH client, or multiplexer could be intercepting either ^P or ^Q (usually the latter). To test whether this is the issue, try running or attaching with the --detach-keys z argument. You should now be able to detach by pressing z, without any modifiers. If this works, another program is interfering. The easiest way to work around this is to set your own detach sequence using the --detach-keys argument. (For example, to exit with ^K, use --detach-keys 'ctrl-k'.) Alternatively, you can attempt to disable interception of the keys in your terminal or other interfering program. For example, stty start '' or stty start undef may prevent the terminal from intercepting ^Q on some POSIX systems, though I haven't found this to be helpful.

Zenexer
  • 18,788
  • 9
  • 71
  • 77
53

I think this should depend on the situation.Take the following container as an example:

# docker run -it -d ubuntu
91262536f7c9a3060641448120bda7af5ca812b0beb8f3c9fe72811a61db07fc
# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
91262536f7c9        ubuntu              "/bin/bash"         5 seconds ago       Up 4 seconds                            serene_goldstine

(1) Use "docker attach" to attach the container:

Since "docker attach" will not allocate a new tty, but reuse the original running tty, so if you run exit command, it will cause the running container exit:

# docker attach 91262536f7c9
exit
exit
# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
91262536f7c9        ubuntu              "/bin/bash"         39 minutes ago      Exited (0) 3 seconds ago                       serene_goldstine

So unless you really want to make running container exit, you should use Ctrl+P + Ctrl+Q.

(2) Use "docker exec"

Since "docker exec" will allocate a new tty, so I think you should use exit instead of Ctrl+P + Ctrl+Q.

The following is executing Ctrl+P + Ctrl+Q to quit the container:

# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  18160  1908 ?        Ss+  04:03   0:00 /bin/bash
root        15  0.0  0.0  18164  1892 ?        Ss   04:03   0:00 bash
root        28  0.0  0.0  15564  1148 ?        R+   04:03   0:00 ps -aux
root@91262536f7c9:/# echo $$
15

Then login container again, you will see the bash process in preavious docker exec command is still alive (PID is 15):

# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  18160  1908 ?        Ss+  04:03   0:00 /bin/bash
root        15  0.0  0.0  18164  1892 ?        Ss+  04:03   0:00 bash
root        29  0.0  0.0  18164  1888 ?        Ss   04:04   0:00 bash
root        42  0.0  0.0  15564  1148 ?        R+   04:04   0:00 ps -aux
root@91262536f7c9:/# echo $$
29
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Nan Xiao
  • 16,671
  • 18
  • 103
  • 164
35

when nothing else works, open a new terminal then:

$ ps aux | grep attach
username  <pid_here>    ..............  0:00 docker attach <CONTAINER_HASH_HERE>
username  <another_pid> ..............  0:00 grep --color=auto attach
$ kill -9 <pid_here>
Adi Fatol
  • 956
  • 15
  • 24
11

To detach from the container you simply hold Ctrl and press P + Q.

To attach to a running container you use:

$ docker container attach "container_name"
Mwiza
  • 7,780
  • 3
  • 46
  • 42
gXg
  • 508
  • 4
  • 6
9

I had the same issue, Ctrl+P and Q would not work, nor Ctrl+C ... eventually I opened another terminal session and I did "docker stop containerid " and "docker start containerid " and it got the job done. Weird.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Pierluigi Vernetto
  • 1,954
  • 1
  • 25
  • 27
  • This won't work if you started the container with `--rm` flag. `Ctrl+P` and `Ctrl+Q` works if you started the container with `-it` flag. – Aswath K Nov 06 '18 at 10:57
6

Update

I typically used docker attach to see what STDOUT was displaying, for troubleshooting containers. I just found docker logs --follow 621a4334f97b, which lets me see the STDOUT whilst also being able to ctrl+c off of it without affecting container operation! Exactly what I've always wanted.

... naturally you'll need to substitue in your own container ID.

Original Answer

I wanted to leave the container running, but had attached without starting the container with -it. My solution was to sacrifice my SSH connection instead (since I was SSHed into the machine that was running the containers). Killing that ssh session left the container intact but detached me from it.

CenterOrbit
  • 6,446
  • 1
  • 28
  • 34
4

In the same shell, hold Ctrl key and press keys P then Q

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
ravthiru
  • 8,878
  • 2
  • 43
  • 52
3

For anyone who ran into the same problem I did (can't detach without killing the container, even when setting the detach key)......

When starting your containers with docker-compose up -d

instead of using docker attach {container name} to view the tailing log ....

try docker-compose logs -f {service name} Ctrl+C kills the log tail without killing your container

{service name} being the service listed in side of your docker-compose.yml file.. (e.g. while container name=elk_logstash_1 -> service name=logstash

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Lon Kaut
  • 2,488
  • 2
  • 11
  • 8
1

I'm on a Mac, and for some reason, Ctrl-p Ctrl-q would only work if I also held Shift

Zoe
  • 27,060
  • 21
  • 118
  • 148
1
  1. Open a new terminal
  2. Find the running container Id docker ps
  3. Kill the container docker kill ${containerId}
1

I found the documentation regarding attaching and detaching a little complicated.

I tried different options to start a container and attach to it from another terminal. The following table summarizes the results:

attachment behavior

It has the following column meaning:

  • -d - is the option docker run -d used or not
  • --sig-proxy - is the option docker attach --sig-proxy=true|false used to not
  • --no-stdin - is the option docker attach [--no-stdin] used to not
  • keys - whether docker send input keys to containerized application or not
  • ^C - what happened when user press Ctrl+C
  • ^P ^Q - what happened when user press Ctrl+P Ctrl+Q

There is a few findings:

  • attachment behavior doesn't depend on -d option but from -i and -t

  • you can consider attach columns either a connection to a container from another terminal (e.g. docker attach --sig-proxy=false and you may vary connection options) or from the current terminal (but you can't vary connection options; --sig-proxy=true)

  • detachment depends on running options and can be done in three ways:

    1. docker run [-i|-t] and connect from another terminal by docker attach --sig-proxy=false CONT -> press Ctrl+C
    2. docker run -it and connect from another terminal by docker attach -> press Ctrl+P Ctrl+Q
    3. docker run -it and connect from another terminal by docker attach --no-stdin -> press Ctrl+C

(of course, you should provide other necessary arguments for commands like a container name or an image)

P.S. I tried different scenarios with -i and -t (only one of them) but didn't get the difference in behavior. I saw that @ken-cochrane provides the following:

docker run -i → cannot be detached with ^P^Q; will disrupt stdin

but I'm not succeeded to reproduce this.

Maxim Suslov
  • 4,335
  • 1
  • 35
  • 29
  • Regarding your last sentence, in order to reproduce it, you can try: 1. `docker run -it alpine sleep 10` - you will be able to detach with `^P^Q` 2. `docker run -i alpine sleep 10` - you will NOT be able to detach with `^P^Q` – Goran Vasic Jul 29 '23 at 18:39
1

If --sig-proxy=false method doesn't work then you can also change the escape sequence using:

docker attach --detach-keys="<sequence>" <container_name or id> 

For example, I want to detach the container using "ctrl-c" then I can attach the container using:

docker attach --detach-keys="ctrl-c" <container_name or id>

The format of the is either a letter [a-Z], or the ctrl- combined with any of the following:

  • a-z (a single lowercase alpha character )
  • @ (at sign)
  • [ (left bracket)
  • \ (two backward slashes)
  • _ (underscore)
  • ^ (caret)

For more information also see -> Override the detach sequence

Zaiban Ali
  • 11
  • 2
0

to stop a docker process and release the ports, first use ctrl-c to leave the exit the container then use docker ps to find the list of running containers. Then you can use the docker container stop to stop that process and release its ports. The container name you can find from the docker ps command which gives the name in the name column. Hope this solves your queries....

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
0

I think @CenterOrbit's answer is spot on, except you get all the history from the logs, which can be a lot to go through if the container's been running for a bit.

Add --tail to it though, and you can specify how much history you want to see, and then continue to read in real-time, or --since to get logs since a particular date, or even both to get either xxx lines, or since a date/time whichever is the more restrictive.

docker logs --follow --tail 500 containerid
docker logs --follow --since 2023-06-14T05:00:00 containerid
docker logs --follow --since 2023-06-14T05:00:00 --tail 500 containerid
Nich Overend
  • 822
  • 8
  • 16
-2

If you only need the docker process to go in the background you can use

Ctrl + Z

Be aware that it is not a real detach and it comes with a performance penalty. (You can return it to foreground with the bg command).

Another option is to just close your terminal, if you don't need it any longer.

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
Tom
  • 1,470
  • 15
  • 13