Bottom line: A restart policy only fires when the container’s main process exits, so a process that stays alive but stops answering requests will sit there indefinitely — you need a HEALTHCHECK to turn “hung” into “unhealthy” and a restart policy to turn “unhealthy” into “restarted.”

Docker’s restart policies are process supervisors, not service supervisors. unless-stopped will happily keep a wedged Node process running for a week because PID 1 never died. The fix is to define a health check that probes the actual serving path, set sane interval, timeout, retries and start_period values, and understand that Docker does not restart unhealthy containers on its own — you need something (Swarm, a compose-level wrapper, or an external watchdog) to act on the health status. This post covers the exact configuration I use and the failure modes I hit getting there.

Restart policies are exit-code handlers

Docker has four restart policies, and they all key off the container’s exit status:

Policy Restarts on non-zero exit Restarts on daemon restart Restarts on manual stop Typical use
no (default) No No No One-shot jobs, debugging
on-failure[:max] Yes, up to max No No Batch workers, cron-like tasks
always Yes Yes Yes Long-running services you always want up
unless-stopped Yes Yes No (respects manual stop) Production services, homelab daemons

The subtlety that bites people: on-failure does not restart on exit code 0, and always/unless-stopped restart regardless of exit code. None of them care whether the process is useful. A container whose app has deadlocked on a mutex, exhausted its connection pool, or lost its database connection but kept the event loop alive has exit code “still running” — and every policy above treats that as healthy.

unless-stopped is the right default for anything you’d be annoyed to find down after a host reboot, because it survives systemctl restart docker but respects a deliberate docker stop. always is almost never what you want on a workstation, because it fights you every time you try to stop something.

The health check is what makes the policy meaningful

A HEALTHCHECK runs a command inside the container on a schedule and records the result as healthy, unhealthy, or starting. Docker does not restart on unhealthy by itself — but the status is visible to orchestration layers, to docker ps, and to anything watching the container. In Swarm mode, an unhealthy task is killed and rescheduled. In plain compose, you wire it to a restart yourself.

The Dockerfile form:

1
2
HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
CMD curl -fsS http://localhost:8080/healthz || exit 1

The flags mean exactly what they say:

  • --interval — time between checks (default 30s).
  • --timeout — how long a single check may run before it counts as a failure (default 30s).
  • --start-period — grace window after container start during which failures don’t count toward retries. Critical for anything with a slow boot.
  • --retries — consecutive failures before the container is marked unhealthy (default 3).

With the values above, a container that hangs at t=0 is marked unhealthy at roughly t = 40s + 3×30s = 130s. That’s the number you tune. Too tight and you restart healthy-but-slow services; too loose and you’re down for minutes before anything notices.

Compose configuration that actually recovers

The compose equivalent, with the restart policy and health check paired:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
services:
api:
image: registry.example.com/api:1.14.2
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-fsS", "http://localhost:8080/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 40s
volumes:
- api-data:/var/lib/api
deploy:
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 5
window: 120s

volumes:
api-data:

Two things to notice. First, restart: unless-stopped and deploy.restart_policy are different mechanisms — the former is the classic engine-level policy, the latter is Swarm’s. In a single-node docker compose up, only restart applies; deploy keys are ignored unless you’re running in Swarm mode. Second, the health check probes /healthz, not /. A health endpoint that returns 200 as long as the HTTP server is listening tells you nothing — it must touch the dependencies the service needs to do its job (database ping, cache round-trip, downstream API reachability) and return non-2xx when any of them fail.

Turning “unhealthy” into “restarted” without Swarm

Plain Docker won’t restart an unhealthy container. If you’re not running Swarm, you need a small watchdog. The simplest reliable version is a cron job or systemd timer that inspects health status and restarts anything stuck:

1
2
3
4
5
6
7
8
#!/usr/bin/env bash
set -euo pipefail

for cid in $(docker ps -q --filter health=unhealthy); do
name=$(docker inspect -f '{{.Name}}' "$cid")
echo "$(date -Is) restarting unhealthy container $name ($cid)"
docker restart "$cid"
done

Run it every minute from a systemd timer:

1
2
3
4
5
6
7
8
9
10
11
# /etc/systemd/system/docker-health-watchdog.timer
[Unit]
Description=Restart unhealthy Docker containers

[Timer]
OnBootSec=2min
OnUnitActiveSec=60s
Unit=docker-health-watchdog.service

[Install]
WantedBy=timers.target

The service unit just runs the script above. This is deliberately blunt — it restarts rather than investigates — but it converts a silent hang into a bounded outage. If you’d rather not restart blindly, log the container’s last 200 log lines before restarting so you have something to debug later.

Health check commands that don’t lie

The check command runs inside the container, so it can only use what’s in the image. That’s the first place people get it wrong: a slim image without curl or wget will fail every check, and the container will flap forever. Options:

  • Use the language runtime you already ship: node -e "require('http').get('http://localhost:8080/healthz',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))".
  • Use wget --spider -q http://localhost:8080/healthz if the base image has BusyBox.
  • Ship a tiny static health binary, or curl in a distroless image via a multi-stage copy.

Also make sure the health endpoint is cheap. A check that runs a full report every 30 seconds will itself become a load source. The pattern I use: /healthz does a SELECT 1 against the database and a PING against Redis, with a hard 2-second timeout on each, and returns 503 if either fails. Everything else — queue depth, disk usage, dependency latency — goes to /metrics, not the health check.

Pitfalls and how to diagnose them

Container marked unhealthy but never restarted. This is the default behaviour. Confirm with docker inspect --format '{{.State.Health.Status}}' <container> — if it says unhealthy and docker ps shows it still running, you have no watchdog. Add one or move to Swarm.

Health check fails because the tool is missing. docker inspect --format '{{json .State.Health}}' <container> shows the last few probe outputs. If you see exec: "curl": executable file not found, the image doesn’t have the binary. Rewrite the check or add the tool.

Start period too short, container flaps on boot. Look for unhealthy transitions in the first minute after docker run. Increase start_period to cover your worst-case cold start, not the average.

Restart loop with no backoff. Docker applies exponential backoff to restart policies (starting at 100ms, doubling, capped at 1 minute), but a container that crashes on startup will still churn. docker events --filter event=restart shows the cadence. If you see restarts every 60s indefinitely, the container is failing its own startup checks — fix the app, don’t loosen the policy.

Volume permissions after restart. A container restarted under a different UID (or after a volume was recreated) can fail to write its data directory and exit immediately, which the restart policy faithfully restarts forever. docker logs --tail 50 <container> usually shows the permission error. Named volumes inherit ownership from the image at creation time; bind mounts do not.

Health check passes but the service is broken. Almost always a shallow probe (/ returning 200). Make the endpoint exercise the actual dependency path.

FAQ

Does Docker restart a container when its health check fails?

No. The restart policy reacts to process exit, not health status. An unhealthy container stays running until something external — Swarm, a watchdog script, or you — restarts it.

What’s the difference between always and unless-stopped?

Both restart on crash and on daemon restart. unless-stopped additionally remembers that you ran docker stop and won’t bring the container back on the next daemon restart; always will.

How long before an unhealthy container is actually restarted?

With start_period: 40s, interval: 30s and retries: 3, the container is marked unhealthy at roughly 130 seconds after start, assuming it never becomes healthy. The restart itself depends on your watchdog interval — with a 60-second timer, add up to another minute.

Can I use depends_on with health checks to order startup?

Yes. depends_on: { db: { condition: service_healthy } } in compose waits for the dependency’s health check to pass before starting the dependent service. This is the correct way to sequence a database and an app; sleeping in an entrypoint is not.

Why does my health check work in docker run but fail in compose?

Usually a missing start_period in one of the two, or a compose file that overrides the image’s HEALTHCHECK with a different test. Compare docker inspect output between the two containers — the Config.Healthcheck block will show which definition won.

Should I use on-failure for a web service?

Only if you want the service to stay down after a clean exit. For anything that should always be running, unless-stopped is the safer default; on-failure is for jobs where exit 0 means “done, don’t restart me.”