Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Docker Restart Policies: no, on-failure, always, and unless-stopped

What each policy really restarts, why on-failure ignores a clean exit, how backoff hides crash loops, and why health checks never trigger a restart.

~5 min readDocker
#Docker#Lifecycle#Production
3D illustration of a container rebooting on an exponential backoff staircase with a circuit breaker switch

Quick Summary

A Docker restart policy answers one question: when the container's main process exits, should the engine start it again, and under what condition. There are four values. no (the default) never restarts. on-failure[:max] restarts only on a non-zero exit code, optionally at most max times. always restarts on any exit and also brings the container back when the daemon starts. unless-stopped behaves like always but remembers a manual docker stop and stays down across daemon restarts.

The policy does not cover what most people assume it covers. A health check failing does not restart a container under any of these policies — only the Swarm/orchestrator restart logic acts on health. A policy also cannot fix an application that fails during dependency startup: it will simply restart forever with the same result. Restarts use an exponential backoff (starting at roughly 100 ms, doubling, capped near one minute in current engine versions) that resets once the container has stayed up, so a permanently broken image produces a slow, quiet crash loop rather than a CPU spike.

Use unless-stopped for long-running services on a single host, on-failure:3 for one-shot jobs where a few retries are legitimate, and no for anything whose lifecycle an orchestrator owns. Then add a health check and monitoring for the states the policy cannot see — running-but-broken.

Basic syntax and query signatures

bash
# Docker CLI docker run -d --restart=unless-stopped --name api my/api:1.4 docker run --restart=on-failure:3 --name migrate my/api:1.4 migrate docker run --restart=no my/api:1.4 # default # Change it on a running container, no restart required docker update --restart=always api # Inspect what is actually configured docker inspect -f '{{.HostConfig.RestartPolicy.Name}} {{.HostConfig.RestartPolicy.MaximumRetryCount}}' api docker inspect -f '{{.RestartCount}} {{.State.Status}} {{.State.ExitCode}}' api

Compose v2 syntax, plus the Swarm form that lives under deploy.

yaml
services: api: image: my/api:1.4 restart: unless-stopped # maps to the same engine policy worker: image: my/worker:1.4 restart: on-failure:5 migrate: image: my/api:1.4 command: ["/app/migrate"] restart: "no" # quote it or YAML reads false
yaml
deploy: restart_policy: condition: on-failure # none | on-failure | any delay: 5s max_attempts: 3 window: 60s

The daemon default can be set once for every container that does not specify its own policy:

json
{ "default-address-pools": [], "restart-policy": "unless-stopped" }

Key comparison table

PolicyRestart on exit 0Restart on non-zeroRestart after docker stopRestart after daemon boot
noNoNoNoNo
on-failureNoYesn/aYes, if it had failed
on-failure:NNoYes, up to Nn/aYes, budget preserved
alwaysYesYesYesYes
unless-stoppedYesYesNo (stays stopped)Yes, unless stopped
ConcernRestart policyHealth checkOrchestrator
Process exitedActs—Acts
Process alive but unresponsiveCannot seeDetects, does not restartRestarts (Swarm/K8s)
Dependency not readyLoops blindlyWaits, then reports unhealthyWaits, then fails
Restart ordering between servicesNoneNonedepends_on + health condition
SettingScopeNote
--restart on docker runOne containerIgnored with --rm
restart: in ComposeOne serviceRecreated on docker compose up
deploy.restart_policySwarm serviceCompose ignores it outside Swarm
docker update --restartLive containerDoes not restart it immediately
live-restore daemon optionHostKeeps containers running across daemon reloads

Practical edge cases and deep dives

1. on-failure and exit code 0: a silent no-restart

An application that exits cleanly when its database is unreachable — quite common for a main that logs an error and returns — will never be restarted by on-failure, because the process reported success.

bash
docker run -d --restart=on-failure:3 my/api:1.4 sleep 5 docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}} restarts={{.RestartCount}}' api # exited exit=0 restarts=0

Make the process exit non-zero on unrecoverable startup failure, or accept that on-failure is the wrong policy for that service.

2. always versus unless-stopped after a daemon restart

bash
docker run -d --restart=always --name a nginx:alpine docker run -d --restart=unless-stopped --name b nginx:alpine docker stop a b sudo systemctl restart docker docker ps --format '{{.Names}} {{.Status}}' # a Up ... (always ignores the manual stop) # b (unless-stopped honours it)

This is the whole reason unless-stopped exists: maintenance stops survive a reboot. always is appropriate only for infrastructure you genuinely never want down, such as a monitoring agent.

3. Crash loops are quiet, and backoff hides them

The restart delay grows, so a container that fails immediately on start settles into a loop of "start, die, wait a minute". docker ps shows Restarting (1) 40 seconds ago, which reads like a transient problem.

bash
docker ps --filter name=api --format '{{.Names}} {{.Status}}' docker events --filter container=api --filter event=restart --since 10m docker logs --tail 50 api # logs survive restarts of the same container id

Alert on RestartCount increasing rather than on the container being absent, because a crash loop is always "present".

4. Restart policies do not order services

With Compose, after docker compose up, a restarted dependency does not bring its dependents back, and a dependent that starts first will fail and restart on its own schedule.

yaml
services: db: image: postgres:16 healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s retries: 12 api: depends_on: db: condition: service_healthy restart: unless-stopped environment: DB_HOST: db

depends_on with service_healthy only affects initial startup order. After a db restart, api keeps running against a broken connection. Application-level retry with backoff — reconnect loops inside the process — is what actually survives, and the restart policy is only the last resort.

5. restart: "no" versus restart: no in YAML

yaml
restart: no # parsed as boolean false -> Compose rejects or coerces it restart: "no" # the policy string

Compose validates the field against the four known values, so the unquoted form fails with an unhelpful services.api.restart must be a string. Quote no and any value with a colon.

6. One-shot jobs: on-failure with a bounded budget

A migration or a batch import should not restart forever; a database that is briefly locked should not fail the deployment.

bash
docker run --rm --restart=on-failure:3 my/api:1.4 /app/migrate

--rm and --restart are mutually exclusive: the engine rejects the combination because a restarted container would have already been removed. Drop --rm and clean up explicitly, or stop retrying and handle it in the entrypoint.

bash
#!/bin/sh # entrypoint retry loop: bounded, visible, with jitter n=0 until /app/migrate; do n=$((n+1)); [ "$n" -ge 3 ] && exit 1 sleep $((n*2)) done

7. Health checks, autoheal and the gap in between

yaml
services: api: image: my/api:1.4 restart: unless-stopped healthcheck: test: ["CMD", "curl", "-fsS", "http://localhost:8080/healthz"] interval: 10s timeout: 3s retries: 3 start_period: 20s

Docker marks the container unhealthy and stops there. To turn that into a restart on a single host, run a small watchdog (the popular willfarrell/autoheal image) that listens to health status events and restarts unhealthy containers. start_period is the piece people forget: without it, a slow boot trips the retry limit and the container is flagged unhealthy before it has finished starting.

Common mistakes and runtime errors

SymptomCauseFix
on-failure never restartsProcess exits with code 0Exit non-zero on failure, or use always
Container restarts after docker stopPolicy is alwaysUse unless-stopped
Container stays down after rebootPolicy no, or stopped with unless-stoppeddocker update --restart=unless-stopped
--rm plus --restart rejectedMutually exclusive flagsChoose one; retry in the entrypoint
Crash loop invisible in docker psBackoff between attemptsAlert on RestartCount and docker events
Unhealthy container never restartedHealth checks do not trigger policiesWatchdog or orchestrator
services.api.restart must be a stringUnquoted no in YAMLrestart: "no"
App fails right after its database restartsdepends_on only orders initial startIn-process reconnect with backoff
Restart policy ignored in SwarmWrong key (restart instead of deploy.restart_policy)Move it under deploy
Logs "missing" after restartNew container, old logs pruned by driver limitsCentralised logging
docker update did not restart the containerUpdate only changes configurationRestart explicitly when needed

Try matching browser tools

All tools

Small utilities that fit Docker work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Docker guides

More in Docker

All Docker guides

The guides filed next to this one in Docker, in library order.