A container is one main process (PID 1) and everything it starts. When PID 1 exits, the container stops. Docker records the exit code.
text
docker run ──► PID 1 starts ──► container Up
│
▼
PID 1 exits ──► container Exited (<PID 1 exit code>)Other processes in the container do not keep it alive. Only PID 1 counts.
Which process is PID 1
docker run ... | PID 1 | Runs until |
|---|---|---|
nginx:1.27 | nginx (image default) | stopped |
redis:7.4 | redis-server (image default) | stopped |
alpine:3.20 | /bin/sh (image default) | stdin closes: at once with -d |
alpine:3.20 echo hi | echo hi | it prints hi |
alpine:3.20 sleep 30 | sleep 30 | 30 seconds pass |
-dit alpine:3.20 | /bin/sh with a terminal | stopped |
The COMMAND column shows PID 1.
Watch it happen
sh
docker run -d --name quick alpine:3.20
docker run -d --name nap alpine:3.20 sleep 30
docker run -dit --name box alpine:3.20
docker ps -a --format 'table {{.Names}}\t{{.Command}}\t{{.Status}}'text
NAMES COMMAND STATUS
box "/bin/sh" Up 2 seconds
nap "sleep 30" Up 4 seconds
quick "/bin/sh" Exited (0) 7 seconds ago30 seconds later:
text
NAMES COMMAND STATUS
box "/bin/sh" Up 34 seconds
nap "sleep 30" Exited (0) 6 seconds ago
quick "/bin/sh" Exited (0) 39 seconds agoquick:/bin/shread end-of-input on stdin and exited 0.nap:sleep 30finished and exited 0.box:-ikeeps stdin open,-tattaches a terminal, so the shell waits.
Read the exit code
| Status | Likely cause |
|---|---|
Exited (0) | the process finished its work, or had nothing to do |
Exited (1), (2), ... | the program reported an error; read docker logs |
Exited (126) | the command exists but cannot be executed |
Exited (127) | the command was not found in the image |
Exited (137) | killed with SIGKILL (docker stop timeout, docker kill, out of memory) |
Design consequences
- A server image's default command must run the server in the foreground. If it forks into the background and exits, the container stops.
- One-off tasks (migrations, reports,
echo) are expected to exit.Exited (0)is success. docker execneeds a running container. You cannot exec intoquickafter it exits.