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.

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.

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

@Khushal gave me the answer... sort of. In my case, Ctrl+P & Ctrl+Q still didn't work even when calling run with -t, but plain old Ctrl+C did. To provide some context, I'm playing with a Rancher docker container, so YMMV.

To summarize, create the container with: docker run -t -d --name=thingy ...

Attach as usual with: docker attach thingy

Detach with good old fashioned Ctrl+C.

By the way, -t, according to the docs, allocates a pseudo-TTY.

This question has been asked previously, Please refer to: How do you attach and detach from Docker's process? - Stack Overflow

In 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?

@BMitch Edited the question to add the -ti flags; sorry for omitting that!

Thanks @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.