How to exit docker exec after container has exited?
Solution 1
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 Ctrl+P & Ctrl+Q sequece and reattached with docker attach
docker run -i → cannot be detached with Ctrl+P & Ctrl+Q sequence; will disrupt stdin
docker run → cannot be detached with Ctrl+P & Ctrl+Q; can SIGKILL client; can reattach with docker attach
Hope this helps.
Solution 2
You first run container with detached mode, not foreground:
docker run --name mynginx -p 80:80 -d nginx
Then you can attach to it with docker exec:
docker exec -it mynginx /bin/sh
Bear in mind that if you want to attach to a container for inspecting, you have to specify --interactive , -i
and --tty , -t
options, because your container is already running your main process in background from your previous docker run -d
command.
That way when you finish inspecting your container, you can gracefully exit from it with ctrl+d
or logout
command, as you exit from an ordinary shell
Jeff Learman
Software Development Engineer musician, erstwhile windsurfer
Updated on September 18, 2022Comments
-
Jeff Learman over 1 year
How do I gracefully exit a docker container that I've connected to using
docker exec -ti
, after the docker I connected to exits?If I exit the original container, the shell that ran the
docker exec
command is hung, and the only way I can find to exit back to its shell is to kill thedocker exec
command from another terminal.Is there a more graceful way?
This happens whether I start the container with
--rm
or not.I'm running docker 19.03.12 under bash 5.0.16 in gnome-terminal 3.26.3 in Ubuntu 20.04.
-
Khushal almost 4 yearsThis question has been asked previously, Please refer to: stackoverflow.com/questions/19688314/…
-
Jeff Learman almost 4 yearsThanks @user929169 -- I didn't know the right terms to use. I can't close this as duplicate since the answer is on another site. Post this as the answer and you'll get the points.
-
BMitch almost 4 yearsIn my own Debian environment running 19.03.11, the exec instance immediately exits and returns my shell prompt as soon as the container exits. Can you provide any more details to reproduce your issue?
-
Jeff Learman almost 4 years@BMitch Edited the question to add the
-ti
flags; sorry for omitting that!
-
-
Jeff Learman almost 4 yearsThanks, but doesn't answer the question I asked.
-
rgio almost 4 yearsSorry I misunderstood
-
Jeff Learman almost 4 yearsnp, and your answer might be helpful for someone with a related question.
-
CptanPanic over 3 yearsThat info is for
docker attach
does this work fordocker exec
?