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 dockerd or containerd restarts, 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 for stdin, stdout, and stderr.
  • Identity: The docker run process is NOT the parent of the container; the container-shim is.

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+C while attached, you usually send a SIGINT to the container’s PID 1, which might stop the entire container. (Use Ctrl+P, Ctrl+Q to 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 exec process does not affect the main container process (PID 1).

Summary Comparison

Featurerunattachexec
Container StateNew (Creates it)Existing (Running)Existing (Running)
Target ProcessPID 1PID 1New Process
Main Use CaseDeployment / TestingLog monitoring / Manual entryDebugging / Side-tasks
Effect of Ctrl+CStops containerStops 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