Why Do Docker Containers Exit Instantly? The Hidden Role of PID 1 Explained
This article explains why Docker containers often stop right after starting by examining the Linux PID 1 init process, the behavior of foreground versus daemonized commands in Dockerfiles, and how container runtimes like containerd‑shim and runc manage the container’s main process.
Many Docker beginners encounter a container that starts and then immediately stops, often thinking the command or Dockerfile is wrong; in reality, Docker executes the process so quickly that it appears to exit without error.
Using the official nginx Dockerfile as an example, the
CMDis set to run
nginx -g 'daemon off;'instead of traditional init commands such as
systemctl nginx startor
/etc/init.d/nginx start. This is because if nginx runs in background mode, the start command finishes, causing the container to exit as well.
To understand why the container exits when the command finishes, we need to look at the Linux kernel’s PID 1 process. After the kernel boots, it starts the
initprocess (PID 1), which becomes the parent of all user‑space processes. Concepts such as process table entries, zombie processes, and orphan processes are tied to PID 1’s responsibility for cleaning up terminated processes.
In a Docker container, however, there is no separate init process; the process marked as PID 1 inside the container is simply the command specified by
CMDor
ENTRYPOINT. For example, running
docker run -d nginxstarts the
nginxprocess as PID 1 inside the container. This occurs because Linux namespaces provide a separate PID namespace, making the container’s main process appear as PID 1.
If the host kills this PID 1 process, the entire container stops, which explains why the container exits when the command completes.
Observing the container’s process tree shows that the parent PID appears as
0, which corresponds to the
containerd‑shimprocess. The container runtime architecture is
docker‑containerd‑shim → runc → entrypoint, but the
runcprocess exits after creating the container, so it is not visible in the running process list.
runcis an OCI‑standard reference implementation that interacts directly with cgroups and the Linux kernel to set up the container’s environment, then launches the specified entrypoint process.
Understanding these details clarifies why Docker containers often exit immediately after launch when the main process finishes.
Efficient Ops
This public account is maintained by Xiaotianguo and friends, regularly publishing widely-read original technical articles. We focus on operations transformation and accompany you throughout your operations career, growing together happily.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.