How to Exit Docker Exec After Container Has Exited

bashcontainersdockerUbuntu

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.

Best Answer

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.