Restart Policies
Container restart policies tell the Docker daemon what to do when a container exits or the host reboots. The four values — no, on-failure, always, unless-stopped — cover most cases. Get this wrong on a long-running daemon and a crash takes the service offline until someone manually starts it.
Set, inspect, and reason about restart policies
EXAMPLE
# 1) Pick the right policy for the workload
# no — default; never restart. Good for one-off batch jobs.
# on-failure — restart when exit code != 0, up to N times. Good for jobs that should retry.
# always — always restart, even on docker daemon restart and manual stop.
# unless-stopped — like 'always', but respects 'docker stop'. Best default for long-running services.
# 2) Apply at run time
docker run -d --name api --restart unless-stopped my/api:1.0
docker run -d --name worker --restart on-failure:5 my/worker:1.0 # max 5 retries
docker run --rm --restart no my/migrate:1.0 # never auto-restart
# 3) Change a running container's policy without recreating it
docker update --restart unless-stopped api
# 4) Inspect what is configured
docker inspect api --format '{{ .HostConfig.RestartPolicy.Name }} (count: {{ .HostConfig.RestartPolicy.MaximumRetryCount }})'
# 5) Restart counter, last exit code, and last restart time
docker inspect api --format \
'RestartCount={{ .RestartCount }} LastExit={{ .State.ExitCode }} StartedAt={{ .State.StartedAt }}'
# 6) Stop the loop manually
docker stop api # 'unless-stopped' will NOT restart after this
docker rm api
# 7) Compose: identical policies, declaratively
# docker-compose.yml
# services:
# api:
# image: my/api:1.0
# restart: unless-stopped
# healthcheck:
# test: ['CMD', 'curl', '-f', 'http://localhost:8080/health']
# interval: 10s
# timeout: 2s
# retries: 3
# start_period: 20s
# 8) Healthcheck + restart = self-healing
# When the healthcheck reports unhealthy, the container is killed by the
# orchestrator and the restart policy brings it back up — clean recovery
# from leaks, deadlocks, and corrupted in-memory state.
# 9) Watch the restart cycle in action
docker events --filter container=api --filter event=restart
Why it matters
For production daemons, default to unless-stopped + a real healthcheck. Always restarts past an explicit `docker stop`, which is rarely what you want; no never recovers from a crash; on-failure stops after the retry limit. unless-stopped is the sweet spot for "stay up unless an operator tells you not to".
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
# Restart policies: no, always, on-failure[:N], unless-stopped docker run -d --restart unless-stopped my-apiTry it Yourself »
Discussion
Loading…