Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
A container is a process with extra plumbing, and like any process it can be created, started, stopped, paused, killed, and removed. The state machine matters because production crashes are diagnosed through exit codes and restart policies, not vibes. Knowing that exit 137 means SIGKILL (usually OOM) and exit 143 means SIGTERM (graceful) is the difference between fixing a bug in five minutes and chasing it for two days.
Walk through every lifecycle transition for a single container and observe the exit code and restart policy in action.
docker run --rm alpine:3.20 sh -c 'exit 42', then echo $? — confirm the container's exit code propagates to the shell.--restart=on-failure:3, force it to exit non-zero three times, and verify Docker stops restarting after the third failure.docker inspect --format '{{.State.OOMKilled}}' to see the OOM flag.Use these three in order. Each builds on the one before.
In one paragraph, explain the lifecycle states a Docker container moves through (created, running, paused, stopped, removed) and what command moves it between them, like I'm new to it.
Walk me through what `docker stop` actually does at the syscall level — SIGTERM, grace period, SIGKILL, exit code propagation — step by step.
Given a production container that keeps exiting with code 137 every few hours, explain how you would diagnose whether it is OOMKilled, evicted, or killed by an external supervisor and what evidence you would collect.
# Create without starting:
docker create --name web -p 8080:80 nginx:1.27-alpine
docker ps -a # STATUS: Created
docker start web
docker ps # STATUS: Up
# Pause/unpause uses the freezer cgroup:
docker pause web
docker exec web echo hi # hangs — process is frozen
docker unpause web
# Stop sends SIGTERM, then SIGKILL after --time seconds (default 10):
docker stop --time 5 web
docker inspect web --format '{{.State.ExitCode}}' # 0 if it caught SIGTERM
# Force-kill (skips graceful shutdown):
docker start web
docker kill web
docker inspect web --format '{{.State.ExitCode}}' # 137 = 128 + SIGKILL
# Restart policies — survive the daemon and node reboots:
docker rm -f web
docker run -d --name web --restart=unless-stopped -p 8080:80 nginx:1.27-alpine
# Memory-limit OOM produces exit 137:
docker run --rm --memory=20m alpine:3.20 sh -c 'a=$(yes | head -c 50M); echo done' \
; echo "exit was $?"
# Clean up everything that has exited:
docker container prune -f