Ensure ‘running’ container is actually healthy and Docker restarts unhealthy containers.
PID 1 running is like a heartbeat - body alive but brain could be dead. Healthchecks check the brain.
Dockerfile:
HEALTHCHECK CMD curl --fail \
http://localhost:8000/healthz || exit 1
docker run:
--restart=unless-stopped
--health-cmd ... --health-interval=10s ...
$ docker ps # STATUS shows 'healthy' / 'unhealthy'
Docker manages container lifecycle with --restart policies: no (default), on-failure[:max] (restart on non-zero exit), always (restart unconditionally; survives daemon restart), unless-stopped (restart unless explicitly stopped). HEALTHCHECK defines a probe; engine runs every N seconds and marks healthy/unhealthy. start_period gives boot time before failures count. Healthchecks don’t restart themselves - orchestration (k8s, ECS) replaces unhealthy ones.
FROM python:3.12-slim
RUN apt-get install -y curl
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
CMD curl --fail http://localhost:8000/healthz || exit 1
defines healthcheck hitting /healthz every 10s; allows 20s start period; 3 retries.
docker run -d --restart=unless-stopped \
--name web myapp:1.0.0
docker inspect --format '{{.State.Health.Status}`}' web
always restart on crash unless explicitly stopped; check status via inspection.
docker update --restart=always web
# updates the restart policy of an already-running container
operator-friendly: update policy of an already-running container.
No restart policy -> container crashes and stays down forever. Healthcheck that always passes (e.g. true). Start-period too short for slow-booting apps. Restart policy always on a stateful service (keeps restarting broken).
--restart=unless-stopped for stateless services; --restart=on-failure for stateful; HEALTHCHECK with a real probe; integrate with structured logging so unhealthy state is debuggable.
Up.docker ps showing high restart count; on-call saw restart storm.--restart=always kept respawning without backoff.on-failure with max-retries=5 and structured backoff.