Skip to content
exec & attach
step 1/5

Reading — step 1 of 5

Read

~1 min readContainer Lifecycle

exec & attach

Two ways to interact with a running container:

docker attach <id> — connect to the container's PID 1 stdin/stdout/stderr.

$ docker attach mybox
nginx logs streaming...
^C    # SIGINT propagates to PID 1, kills nginx, container exits

It's a direct connection. Detaching needs a special escape sequence (Ctrl-P Ctrl-Q by default) to avoid SIGINT killing the container.

docker exec <id> <cmd> — fork a NEW process inside the container's namespaces.

$ docker exec -it mybox bash
root@mybox:/# ls

Internally:

  1. Find the container's namespaces from its PID 1 in /proc/<pid>/ns/
  2. setns() into each (PID, mount, net, etc.)
  3. fork; child execs the new command in the namespaces
  4. Parent process (the docker exec CLI) connects stdin/stdout

The new process is NOT a child of PID 1 inside the container. From inside, ps shows it as PPID=0 (or its inherited parent from outside the container).

Common confusion: docker exec does NOT activate cgroups by default. The exec'd process is in the container's namespaces but typically NOT in the container's cgroups (unless you opt-in).

For this lesson: model attach + exec.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…