Container lifecycle and restart policies

Docker · lesson 15 of 31 · 3 min read

Follow a container through created, running, exited and removed, then pick a restart policy.

Open this lesson in the learning hub

Key points

  • A container is created, running, then exited. docker ps hides exited ones; -a shows them.
  • A container lives exactly as long as its PID 1. When java returns, the container exits with that same exit code.
  • --restart=on-failure:3 retries only non-zero exits, waiting 100 ms, then 200 ms, then 400 ms, capped at one minute.
  • unless-stopped survives a daemon restart but respects a manual docker stop. always ignores even that.
  • A crash loop is not a policy problem. Read RestartCount from docker inspect, then read the last logs.

Example

# where is it, and why did it stop?
docker ps                 # running only
docker ps -a              # includes Exited (1) 3 minutes ago
docker inspect --format "{{.State.Status}} {{.State.ExitCode}} {{.RestartCount}}" api

# retry a flaky start, but give up eventually
docker run -d --name api --restart=on-failure:3 -p 8080:8080 myapp:1.0

# a long-lived service on a dev box
docker run -d --name db --restart=unless-stopped postgres:16

# stream what happens to every container on the host
docker events --filter type=container --filter container=api

The container ends when PID 1 ends. A restart policy retries, it does not fix.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Docker course, and every lesson in it is listed on the Docker contents page.