Restart Policies
Programs crash, hosts reboot and the Docker daemon gets upgraded. A restart policy tells the Docker Engine what
to do when a container's main process exits: leave it stopped, or start it again. In Compose you set it per service
with restart:. Important: the policy is enforced by the engine, not by Compose. Once up -d has created the
containers, Compose can exit; the engine keeps restarting them, also after a reboot. (The Docker course covers
--restart in Restart Policies; this lesson focuses on Compose.)
The four policies
restart: |
Restarts after a crash (non-zero exit)? | After a clean exit (0)? | After docker compose stop, then a daemon restart/reboot? |
|---|---|---|---|
no (default) |
no | no | no |
on-failure[:N] |
yes (at most N times, if given) | no | no |
always |
yes | yes | yes, it comes back |
unless-stopped |
yes | yes | no, it stays stopped |
services:
proxy:
image: nginx:1.29
restart: unless-stopped
worker:
image: shop/worker:1.4
restart: on-failure:5
migrate:
image: shop/api:1.4
command: ["python", "manage.py", "migrate"]
restart: no
metrics:
image: prom/node-exporter:v1.9.1
restart: alwaysname: demo
services:
metrics:
restart: always
image: prom/node-exporter:v1.9.1
networks:
default: null
migrate:
restart: 'no'
command:
- python
- manage.py
- migrate
image: shop/api:1.4
networks:
default: null
proxy:
restart: unless-stopped
image: nginx:1.29
networks:
default: null
worker:
restart: on-failure:5
image: shop/worker:1.4
networks:
default: null
networks:
default:
name: demo_default
restart: no is quoted as 'no' in the output. In YAML 1.1, a bare no means false, so config quotes it to
keep the file unambiguous for every parser. Writing restart: "no" yourself avoids any doubt.
Typos are only caught at start time
config checks that restart is a string, not that it is a known policy. An invalid value passes:
services:
api:
image: shop/api:1.4
restart: sometimesname: demo
services:
api:
restart: sometimes
image: shop/api:1.4
networks:
default: null
networks:
default:
name: demo_default
The engine rejects it only when the container is created:
$ docker compose up -d
[+] Running 1/2
✔ Network demo_default Created 0.1s
⠿ Container demo-api-1 Creating 0.0s
Error response from daemon: invalid restart policy 'sometimes'(Sample output.) A reason to run a real up in CI, not only config.
Restart policies and healthchecks
A restart policy reacts to the process exiting. A container that is running but unhealthy (deadlocked, stuck on a lost connection) is not restarted by plain Docker or Compose. Common remedies:
- make the application exit when it detects that it can't recover, and let the policy restart it;
- add a sidecar such as
autohealthat restarts containers labelled for it when they turn unhealthy; - move to Swarm or Kubernetes, which replace unhealthy tasks or pods automatically.
The back-off
When a container keeps crashing, the engine waits between restarts: 100 ms, then double each time, up to one minute.
If the container then stays up for at least 10 seconds, the delay resets. docker compose ps shows such a service
as Restarting (1) 4 seconds ago. The model reproduces that schedule for a container that crashes after 2 seconds
several times, then runs fine for a while, then crashes again:
def backoff(run_times, policy="always", max_retries=None):
delay, restarts, t = 0.1, 0, 0.0
for i, runtime in enumerate(run_times):
t += runtime
exit_code = 1
if runtime >= 10:
delay = 0.1 # it stayed up long enough: reset the back-off
if policy == "no" or (policy == "on-failure" and exit_code == 0):
print(f"t={t:7.1f}s exit {exit_code}, policy {policy}: stays stopped")
return
if max_retries is not None and restarts >= max_retries:
print(f"t={t:7.1f}s exit {exit_code}, {restarts} restarts used: gives up")
return
print(f"t={t:7.1f}s exit {exit_code} after {runtime:>4}s -> restart in {delay:g}s")
t += delay
restarts += 1
delay = min(delay * 2, 60)
print("restart: always")
backoff([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 300, 2])
print("restart: on-failure:3")
backoff([2, 2, 2, 2], policy="on-failure", max_retries=3)restart: always
t= 2.0s exit 1 after 2s -> restart in 0.1s
t= 4.1s exit 1 after 2s -> restart in 0.2s
t= 6.3s exit 1 after 2s -> restart in 0.4s
t= 8.7s exit 1 after 2s -> restart in 0.8s
t= 11.5s exit 1 after 2s -> restart in 1.6s
t= 15.1s exit 1 after 2s -> restart in 3.2s
t= 20.3s exit 1 after 2s -> restart in 6.4s
t= 28.7s exit 1 after 2s -> restart in 12.8s
t= 43.5s exit 1 after 2s -> restart in 25.6s
t= 71.1s exit 1 after 2s -> restart in 51.2s
t= 124.3s exit 1 after 2s -> restart in 60s
t= 484.3s exit 1 after 300s -> restart in 0.1s
t= 486.4s exit 1 after 2s -> restart in 0.2s
restart: on-failure:3
t= 2.0s exit 1 after 2s -> restart in 0.1s
t= 4.1s exit 1 after 2s -> restart in 0.2s
t= 6.3s exit 1 after 2s -> restart in 0.4s
t= 8.7s exit 1, 3 restarts used: gives up
The delay climbs 0.1 → 0.2 → … → 51.2 s and then is capped at 60 s; after the 300-second run it starts again at
0.1 s. With on-failure:3, the fourth crash is final.
Which events trigger a restart?
The table at the top hides a subtlety: the difference between always and unless-stopped only shows when you
stopped the container and then the daemon restarts (an upgrade or a reboot). The model plays the same sequence of
events against every policy:
def run(policy, events):
state, stopped_by_user, max_retries, failures = "running", False, None, 0
if policy.startswith("on-failure:"):
policy, max_retries = "on-failure", int(policy.split(":")[1])
log = []
for event in events:
if event.startswith("exit"):
code = int(event.split()[1])
if code != 0:
failures += 1
restart = (policy in ("always", "unless-stopped")
or (policy == "on-failure" and code != 0
and (max_retries is None or failures <= max_retries)))
state = "running" if restart else "exited"
elif event == "compose stop":
state, stopped_by_user = "exited", True
elif event == "compose start":
state, stopped_by_user = "running", False
elif event == "daemon restart":
if policy == "always" or (policy == "unless-stopped" and not stopped_by_user):
state = "running" if state == "running" or policy == "always" else state
else:
state = "exited"
log.append(state[0].upper())
return " ".join(log)
events = ["exit 1", "exit 0", "compose start", "compose stop", "daemon restart"]
print(f"{'events:':16}", " | ".join(events))
for policy in ["no", "on-failure", "on-failure:1", "always", "unless-stopped"]:
print(f"{policy:16}", run(policy, events), " (R = running, E = exited)")events: exit 1 | exit 0 | compose start | compose stop | daemon restart
no E E R E E (R = running, E = exited)
on-failure R E R E E (R = running, E = exited)
on-failure:1 R E R E E (R = running, E = exited)
always R R R E R (R = running, E = exited)
unless-stopped R R R E E (R = running, E = exited)
Read the columns: after a crash (exit 1) everything except no restarts; after a clean exit 0 only always
and unless-stopped do; after a manual stop followed by a daemon restart, only always brings the container back.
Which policy to choose
| Service | Policy | Why |
|---|---|---|
| Long-running servers in production (proxy, API, DB) | unless-stopped |
survives crashes and reboots, respects a deliberate stop |
| Agents that must always run (log shipper, node exporter) | always |
comes back even after a manual stop + reboot |
| Workers that may exit on purpose when done | on-failure (optionally :N) |
retries crashes, accepts success |
| One-off jobs (migrations, seeds, tests) | no |
a job should run once; let depends_on check its result |
| Local development | usually no |
a crash loop hides the error; you want to see it |
deploy.restart_policy
The deploy section has its own, richer restart_policy, designed for Swarm:
services:
worker:
image: shop/worker:1.4
deploy:
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 2mname: demo
services:
worker:
deploy:
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 2m0s
image: shop/worker:1.4
networks:
default: null
networks:
default:
name: demo_default
Its conditions are named differently (none, on-failure, any), and delay, max_attempts and window (how
long a task must run to count as a success) give finer control. (Durations are normalised here too: 2m became 2m0s.) Swarm uses it; plain Compose maps the condition and
max_attempts onto the engine's policy when no restart key is set and ignores the rest. For a file used only
with Compose, restart: is clearer. If you plan to deploy the same file as a stack, see
From Compose to Swarm.
Learn more: Healthchecks · depends_on & Startup Order · Compose in Production
Test yourself
You stop a service with docker compose stop and then reboot the host. Which policy brings it back?
- unless-stopped
- always
- on-failure
- no
Does docker compose config reject restart: sometimes?
- Yes, with a schema error
- No; the engine rejects it when the container is created
- No, and the engine treats it as always
- It replaces it with no
A container is running but unhealthy. What does restart: unless-stopped do?
- Restarts it immediately
- Nothing: restart policies react to the process exiting, not to health
- Restarts it after three failed checks
- Stops it