TExcelTAD
Home › Docker › Restart Policies

Restart Policies

Processes crash. Servers reboot. A restart policy tells the Docker daemon what to do when a container's main process exits, so a crashed service comes back on its own without you running docker start.

bash
docker run -d --restart unless-stopped --name api shop-api:1.4
docker update --restart on-failure:5 api          # change it on an existing container
docker inspect --format '{{.HostConfig.RestartPolicy.Name}} {{.RestartCount}}' api
Policy Restarts when the process exits… After docker stop? After the daemon/host restarts?
no (default) never - not started
on-failure[:N] with a non-zero exit code (at most N times) no started again if it was running before
always for any reason not right away, but it does start again when the daemon restarts yes
unless-stopped for any reason no, and it stays stopped after a daemon restart yes, unless you stopped it

In Compose: restart: unless-stopped (or no, always, on-failure, on-failure:3).

Back-off between restarts

To avoid hammering a crashing service, Docker waits longer before each restart: starting at 100 ms and doubling each time, up to a maximum of one minute. The delay resets once the container has stayed up for at least 10 seconds. A crash loop therefore shows as Restarting (1) 12 seconds ago in docker ps.

python · try it yourself
def restart_delays(crashes, max_delay=60.0):
    delay, out = 0.1, []
    for _ in range(crashes):
        out.append(delay)
        delay = min(delay * 2, max_delay)
    return out

delays = restart_delays(12)
elapsed = 0
for n, d in enumerate(delays, start=1):
    elapsed += d
    print(f"restart {n:>2}: wait {d:>6.1f}s   (total {elapsed:7.1f}s)")
restart  1: wait    0.1s   (total     0.1s)
restart  2: wait    0.2s   (total     0.3s)
restart  3: wait    0.4s   (total     0.7s)
restart  4: wait    0.8s   (total     1.5s)
restart  5: wait    1.6s   (total     3.1s)
restart  6: wait    3.2s   (total     6.3s)
restart  7: wait    6.4s   (total    12.7s)
restart  8: wait   12.8s   (total    25.5s)
restart  9: wait   25.6s   (total    51.1s)
restart 10: wait   51.2s   (total   102.3s)
restart 11: wait   60.0s   (total   162.3s)
restart 12: wait   60.0s   (total   222.3s)

A restart-policy simulator

The model applies each policy to the same scenarios: two crashes followed by a clean exit; a manual docker stop followed by a reboot of the host; and a container that keeps crashing under on-failure:2.

python · try it yourself
def simulate(policy, events, max_retries=None):
    running, stopped_by_user, retries, log = True, False, 0, []
    for event in events:
        if event == "reboot":
            should_start = policy in ("always",) or (policy == "unless-stopped" and not stopped_by_user) \
                or (policy.startswith("on-failure") and running)
            running = should_start
            if should_start:
                stopped_by_user = False
            log.append("boot:" + ("start" if should_start else "stay down"))
            continue
        if not running:
            log.append(f"{event}:-")
            continue
        if event == "docker stop":
            running, stopped_by_user = False, True
            log.append("stop:stopped")
            continue
        code = int(event.split()[1])                    # "exit 0" / "exit 1"
        restart = (policy in ("always", "unless-stopped")
                   or (policy == "on-failure" and code != 0
                       and (max_retries is None or retries < max_retries)))
        if restart:
            retries += 1
        running = restart
        log.append(f"exit {code}:{'restart' if restart else 'down'}")
    return log

events = ["exit 1", "exit 1", "exit 0"]
for policy in ["no", "on-failure", "always", "unless-stopped"]:
    print(f"{policy:<15} {simulate(policy, events)}")

print()
events = ["docker stop", "reboot"]
for policy in ["on-failure", "always", "unless-stopped"]:
    print(f"{policy:<15} {simulate(policy, events)}")

print()
print("on-failure:2   ", simulate("on-failure", ["exit 1"] * 4, max_retries=2))
no              ['exit 1:down', 'exit 1:-', 'exit 0:-']
on-failure      ['exit 1:restart', 'exit 1:restart', 'exit 0:down']
always          ['exit 1:restart', 'exit 1:restart', 'exit 0:restart']
unless-stopped  ['exit 1:restart', 'exit 1:restart', 'exit 0:restart']

on-failure      ['stop:stopped', 'boot:stay down']
always          ['stop:stopped', 'boot:start']
unless-stopped  ['stop:stopped', 'boot:stay down']

on-failure:2    ['exit 1:restart', 'exit 1:restart', 'exit 1:down', 'exit 1:-']

The middle block shows the difference between always and unless-stopped: after a manual stop and a reboot, always comes back, unless-stopped respects your decision.

Which policy to choose

Workload Policy
Long-running services on a single host (web app, database, reverse proxy) unless-stopped
Batch jobs that should retry on errors but finish eventually on-failure:3
One-off commands, tests, migrations no (and --rm)
Anything managed by Swarm/Kubernetes let the orchestrator handle restarts (deploy.restart_policy / pod restartPolicy)

Restarts are not a fix

  • A container that restarts every few seconds is crash-looping. Look at docker logs api and the exit code; a restart policy only hides the problem.
  • Restart policies react to the process exiting, not to failed healthchecks. Plain Docker doesn't restart an unhealthy container that is still running (Swarm and Kubernetes do).
  • If a dependency (database) is down, many apps exit at start-up. With a restart policy they retry automatically, which is often good enough on a single host.

Test yourself

You docker stop a container with --restart always, then the host reboots. What happens?

  1. It stays stopped
  2. It starts again when the Docker daemon starts
  3. It is deleted
  4. It restarts every second

With --restart on-failure, the app exits with code 0. Does Docker restart it?

  1. Yes
  2. No, on-failure only restarts on non-zero exit codes
  3. Only 3 times
  4. Only after a reboot

Why does a crash-looping container restart less and less often?

  1. Docker gives up after 5 tries
  2. Docker doubles the delay before each restart, up to a maximum
  3. The host slows down
  4. Logs fill up