What is the difference between docker exec and docker attach?
docker exec starts a new process inside a running container, such as a shell. docker attach connects your terminal to the container's existing main process, so exiting it can stop the container.
Explain it simply
Imagine a running train. docker exec is a TTE boarding at a station and walking through a coach: a new person inside the train, who can leave without affecting it. docker attach is plugging a microphone into the driver's cabin. You hear and talk to the driver, and if you press Ctrl+C you may stop the train itself.
With exec you pick the command: docker exec -it web sh opens a shell next to nginx. Closing that shell leaves nginx running. With attach you see the stdout and stdin of PID 1, the process started by CMD or ENTRYPOINT. If you send Ctrl+C there, the signal can reach the main process and the container stops. Detach safely with the key sequence Ctrl+P then Ctrl+Q.
For debugging, exec is almost always what you want.
Example
docker exec -it web sh # new shell, safe to exit
docker exec web cat /etc/nginx/nginx.conf
docker attach web # view main process output
# detach without stopping: Ctrl+P, Ctrl+QWhat to say in the interview
"exec runs a new command inside a running container and is the normal way to debug. attach hooks my terminal to the main process, so Ctrl+C can stop the whole container. I use exec -it with sh or bash."
Common mistakes
- Using attach for debugging and accidentally stopping the container.
- Forgetting -it, so the shell exits immediately.