Docker: Run vs. Attach vs. Exec
The relationship between docker run, docker attach, and docker exec is a common point of confusion. Understanding their internals reveals why they behave differently and when to use each.
The Docker Execution Chain
When you interact with a container, you aren’t talking to the process directly. There is a layered relay:
Terminal <-> Docker CLI <-> dockerd <-> containerd <-> container-shim <-> Container Process
- Shim: The crucial component that stays alive even if
dockerdorcontainerdrestarts, maintaining the container’s exit status and open file descriptors (stdio).
1. Docker Run
docker run is the command for creating and starting a new container.
- Mechanism: It instructs the daemon to pull an image (if needed), create a container, and start its primary process (PID 1).
- Foreground Simulation: If run without
-d, the CLI creates a bidirectional relay forstdin,stdout, andstderr. - Identity: The
docker runprocess is NOT the parent of the container; thecontainer-shimis.
2. Docker Attach
docker attach allows you to view or interact with the primary process (PID 1) of a currently running container.
- Mechanism: It connects your terminal’s stdio to the container’s existing PID 1 process.
- Limitation: If you attach to a process that isn’t designed for interaction (like a background web server), you might see output but won’t be able to “type” anything useful.
- Risk: If you
Ctrl+Cwhile attached, you usually send aSIGINTto the container’s PID 1, which might stop the entire container. (UseCtrl+P, Ctrl+Qto detach without stopping).
3. Docker Exec
docker exec starts a new, additional process inside an already running container.
- Mechanism: It creates a completely new process tree within the container’s namespaces.
- Use Case: Debugging, running a shell inside a container, or triggering maintenance tasks (e.g.,
docker exec -it my_db psql). - Isolation: Killing an
execprocess does not affect the main container process (PID 1).
Summary Comparison
| Feature | run | attach | exec |
|---|---|---|---|
| Container State | New (Creates it) | Existing (Running) | Existing (Running) |
| Target Process | PID 1 | PID 1 | New Process |
| Main Use Case | Deployment / Testing | Log monitoring / Manual entry | Debugging / Side-tasks |
| Effect of Ctrl+C | Stops container | Stops container (usually) | Stops the exec process only |
Visualizing stdio Streams
Containers treat processes as background daemons by default. The Docker CLI simulates the “foreground” feel by relaying streams through the container-shim. This architecture ensures that even if the Docker daemon crashes, the containerized application continues to run and its output is buffered.
Source: Docker Run, Attach, and Exec Internals - iximiuz Tags: docker containers linux internals