How to exit docker exec after container has exited?

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 the docker 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.


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