Docker Tutorial · Production Practices · Lesson 24 of 26

Healthchecks and Restart Policies

Let Docker detect unhealthy containers and restart crashed ones automatically.

Create a free account to save this page, take notes and track your progress. Sign in

HEALTHCHECK

A healthcheck is a command Docker runs inside the container periodically; its exit code sets the status to healthy or unhealthy:

HEALTHCHECK --interval=10s --timeout=3s --retries=3 CMD wget -qO- http://localhost:8000/health || exit 1

Restart policies

Policy Behaviour
no (default) Never restart
on-failure[:5] Restart when the exit code is non-zero (up to 5 times)
unless-stopped Always restart, except after a manual stop
always Always restart

Plain Docker doesn't restart unhealthy containers; orchestrators (Kubernetes, Swarm, ECS) act on health.

Restart on failure and health status
trap 'docker rm -f rc-flaky rc-hc > /dev/null 2>&1' EXIT
docker run -d --name rc-flaky --restart on-failure:2 alpine:3.24 sh -c 'echo "crashing"; exit 1' > /dev/null
sleep 4
docker inspect rc-flaky --format 'restarts: {{.RestartCount}}, status: {{.State.Status}}'
docker run -d --name rc-hc --health-cmd 'test -f /tmp/ready' --health-interval 1s --health-retries 1 alpine:3.24 sleep 300 > /dev/null
sleep 3; docker inspect rc-hc --format 'before ready file: {{.State.Health.Status}}'
docker exec rc-hc touch /tmp/ready; sleep 2
docker inspect rc-hc --format 'after ready file:  {{.State.Health.Status}}'

Output

restarts: 2, status: exited
before ready file: unhealthy
after ready file:  healthy

Run this on your computer — see “Get Started” for setup.

Test yourself

Does Docker Engine restart a container just because it became unhealthy?

  1. Yes, always
  2. No; restart policies react to exits, orchestrators act on health
  3. Only with --restart always
  4. Only in Compose
Show answer

Answer: No; restart policies react to exits, orchestrators act on health

Health status is information for orchestrators and load balancers.

Was this page helpful?