Quiz Entry - updated: 2026.11.10
What is the difference between docker attach and docker exec, and why does a container stop when you type exit after docker attach?
attach connects your terminal to the container's existing main process; exec starts a new, additional process. Exiting the main process ends the container, which then shows as Exited.
A container lives exactly as long as its main process (PID 1, the CMD or ENTRYPOINT).
docker attach alpine1plugs your terminal into that main process, here theshstarted bydocker run -itd … alpine sh. Typingexitends that shell, so PID 1 ends, so the container moves to Exited. To leave without stopping it, use the detach key sequence Ctrl-P, Ctrl-Q.docker exec -it alpine1 shstarts a second shell next to the main process.exitonly ends that extra shell; the container keeps running.
For looking around inside a running service (an nginx or a database container), exec is almost always what you want: attaching to nginx's main process and pressing Ctrl-C would stop the web server.
Go deeper:
Docker Docs: docker container attach — the detach key sequence and what attaching means.
Docker Docs: docker container exec — running an extra command in a running container.