| |

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

⏱️ Estimated read: 15 min | |

A container that exits is not always a container that should stay exited. A web server that crashes because of a transient network error should come back. A database that is killed by the OOM killer should restart. A batch job that completes successfully should stay stopped. Docker’s restart policies are the mechanism that distinguishes between these cases. They control whether the Docker daemon restarts a container after it exits, and under what conditions.

The four policies are no, on-failure, always, and unless-stopped. They differ in two dimensions: what triggers a restart (any exit, only failure exits, never) and what happens across a daemon restart (a system reboot or Docker upgrade). The on-failure policy is the only one that looks at the exit code. The always and unless-stopped policies ignore the exit code and restart on any exit. The difference between them appears only when a container has been manually stopped and the daemon restarts: always brings it back, unless-stopped leaves it stopped .

The most common misunderstanding is that restart policies have anything to do with health status. They do not. A restart policy reacts to the container’s main process exiting. An unhealthy-but-running container is never restarted by any policy. The restart policy and the healthcheck are independent mechanisms .

This chapter covers three areas. First, why restart policies exist — the difference between a clean exit and a failure, and the problem of surviving daemon restarts. Second, how each policy works — the exact trigger conditions, the on-failure retry limit, the exponential backoff, and the manual-stop behavior. Third, how restart policies interact with Compose and Swarm — the restart: key in Compose, the restart_policy in Swarm, and the common pitfalls that cause a policy to appear to not work. The chapter ends with a complete example session, a quick reference, best practices, common pitfalls, real-world examples, and diagrams showing the decision flow for each policy.

Key point: Restart policies control whether Docker restarts a container after it exits. no never restarts. on-failure restarts only on non-zero exit codes. always restarts on any exit and across daemon restarts, even after a manual stop. unless-stopped is like always but respects manual stops across daemon restarts. Restart policies react to process exit, not health status .


Why restart policies exist

The clean-exit problem. A container’s exit code is a signal. Exit code 0 means the process completed successfully. Exit code non-zero means it failed. For a batch job, exit 0 is the expected outcome, and the container should stay stopped. For a long-running service, any exit is unexpected, and the container should restart. The on-failure policy makes this distinction. It restarts only when the exit code is non-zero, which means a successfully completed job stays stopped and a crashed service comes back .

The daemon-restart problem. Containers do not survive a Docker daemon restart unless a restart policy tells them to. When the daemon stops — during a system reboot, a Docker upgrade, or a manual systemctl restart docker — every running container is stopped. When the daemon starts again, it checks which containers should be running. The restart policy determines which ones are brought back. always and unless-stopped bring their containers back. on-failure does not, because a daemon restart is a clean stop, not a failure . This is the single most confusing aspect of restart policies: on-failure sounds like it should be more reliable, but it actually survives fewer scenarios than unless-stopped.

The manual-stop problem. A user stops a container with docker stop to perform maintenance. Should it come back when the daemon restarts? The answer depends on intent. If the stop was deliberate, the container should stay stopped. unless-stopped honors this. always does not: it brings the container back on the next daemon restart, even though the user explicitly stopped it . The distinction matters for services that are occasionally taken down for maintenance. unless-stopped is the safer default because it respects the operator’s explicit decision .

The restart-loop problem. A container that crashes immediately on startup will, under an aggressive restart policy, restart immediately, crash again, and repeat. This consumes CPU and floods the logs. Docker mitigates this with an exponential backoff: the first restart is delayed by 100ms, the second by 200ms, the third by 400ms, and so on, doubling up to a maximum of one minute . The backoff resets after the container runs successfully for 10 seconds . This prevents a broken container from consuming the host’s resources with rapid restart attempts.

The on-failure-doesn’t-survive-reboot problem. Many people choose on-failure because it sounds more careful than always. They then discover that after a reboot, every container is stopped. The reason is that a system shutdown is not a failure. systemd stops the Docker daemon, and the daemon deliberately stops each container with exit code 0. The on-failure policy sees a clean exit and does not restart. The container stays in the Exited (0) state indefinitely . This is the policy working as designed, but it is not what most people want for long-running services.

The trade-off. unless-stopped is the best default for most production services because it balances automatic recovery with respect for manual intervention . always is appropriate for containers that should never be down, even if an operator tried to stop them — but this can be surprising and difficult to override. on-failure is appropriate for jobs and workers that should restart a limited number of times on failure but not survive a reboot. no is appropriate for interactive containers and development. The choice is not about which policy is “best” but about which failure semantics match the workload.


a. The four policies

Each policy answers two questions: what triggers a restart and what happens across a daemon restart.

no is the default. The container is never restarted, regardless of the exit code or daemon state. This is the correct policy for interactive containers, development, and batch jobs where a restart would be wrong .

on-failure[:max-retries] restarts the container only when it exits with a non-zero code. The optional max-retries limits the number of restart attempts. If the limit is reached, the container stays stopped. The policy does not restart the container when the daemon restarts, because a daemon restart is a clean stop (exit 0), not a failure .

docker run --restart on-failure:5 myapp

The :5 means Docker will attempt to restart the container up to five times after a failure. If the container fails a sixth time, it stays stopped.

always restarts the container on any exit, regardless of the exit code. It also restarts the container when the daemon restarts, even if the container was manually stopped with docker stop. The only way to stop an always container permanently is to remove it or change its policy .

docker run --restart always myapp

unless-stopped is like always, except that a manually stopped container stays stopped across daemon restarts. If the container is running and the daemon restarts, it comes back. If the container was stopped with docker stop, it stays stopped .

docker run --restart unless-stopped myapp

The difference between always and unless-stopped is only visible after a manual stop followed by a daemon restart:

Scenarioalwaysunless-stopped
Container crashesRestartsRestarts
docker stop, then docker startRunsRuns
docker stop, then rebootRestartsStays stopped
Daemon restarts while runningRestartsRestarts

This table is the entire distinction. unless-stopped respects the operator’s explicit stop. always does not .

b. The restart backoff

When a container is restarted repeatedly, Docker does not restart it immediately each time. It applies an exponential backoff to prevent rapid restart loops from consuming excessive resources .

The sequence is:

  1. First restart: immediate (or 100ms)
  2. Second restart: 200ms delay
  3. Third restart: 400ms delay
  4. Fourth restart: 800ms delay
  5. And so on, doubling each time, up to a maximum of 1 minute

The backoff resets after the container runs successfully for 10 seconds. The same 10-second threshold determines whether a container has “started successfully” for the purposes of the restart policy .

During the backoff period, the container is in the Restarting state. You cannot docker exec into it while it is restarting. The docker ps output shows Restarting (1) 2 seconds ago or similar, and the restart count is visible in docker inspect .

c. Compose and Swarm differences

In Docker Compose, the restart policy is set with the restart: key in the service definition:

services:
  app:
    image: myapp
    restart: unless-stopped

In Docker Swarm, the restart: key is ignored. Swarm uses restart_policy: under the deploy: key, which has more options:

services:
  app:
    image: myapp
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 120s

The condition accepts none, on-failure, or any. The delay is the time between restart attempts. The max_attempts limits retries. The window is the time window for evaluating whether a restart was successful .

A common pitfall is editing the restart: value in compose.yaml and running docker compose restart. The restart policy is stored in the container, not the YAML file. docker compose restart only stops and starts the existing container; it does not recreate it with the new policy. The policy change takes effect only after docker compose up -d recreates the container .


Complete Example Session

# ============================================
# PART 1: THE DEFAULT — NO RESTART
# ============================================

# No --restart flag means the default policy is no.
# The container exits and stays exited.

docker run -d --name nginx-default nginx
# (container crashes or is stopped)
# (it does not restart)


# ============================================
# PART 2: ON-FAILURE — RESTART ONLY ON ERROR
# ============================================

# The container restarts only if it exits with a
# non-zero code. A clean exit (0) stays stopped.

docker run -d --name nginx-failure --restart on-failure nginx

# With a retry limit:
docker run -d --name worker --restart on-failure:5 myworker


# ============================================
# PART 3: ALWAYS — RESTART ON ANY EXIT
# ============================================

# The container restarts regardless of exit code.
# It also restarts on daemon restart, even if
# it was manually stopped.

docker run -d --name nginx-always --restart always nginx

# After docker stop, the container is stopped.
# After a daemon restart, it runs again.


# ============================================
# PART 4: UNLESS-STOPPED — RESPECTS MANUAL STOPS
# ============================================

# Like always, but a manual stop persists across
# daemon restarts.

docker run -d --name nginx-unless --restart unless-stopped nginx

# docker stop nginx-unless
# reboot
# (container stays stopped)


# ============================================
# PART 5: THE ON-FAILURE REBOOT TRAP
# ============================================

# on-failure does NOT survive a reboot.
# The daemon stops the container cleanly (exit 0),
# so the policy sees no failure and does not restart.

docker run -d --name db --restart on-failure postgres
# reboot
# docker ps -a
# (db is Exited (0))


# ============================================
# PART 6: THE BACKOFF SEQUENCE
# ============================================

# A crashing container shows the exponential backoff:
# restart 1: immediate
# restart 2: 200ms delay
# restart 3: 400ms delay
# restart 4: 800ms delay
# ...
# restart N: up to 1 minute

docker run -d --name crash --restart always busybox sh -c "exit 1"
docker logs -f crash
# (observe the increasing delays between restarts)


# ============================================
# PART 7: CHANGING THE POLICY ON A RUNNING CONTAINER
# ============================================

# docker update changes the policy without recreating.

docker update --restart unless-stopped nginx-default


# ============================================
# PART 8: THE COMPOSE RESTART GOTCHA
# ============================================

# Editing restart: in compose.yaml does NOT change
# the policy on an existing container.

# compose.yaml
# services:
#   app:
#     image: myapp
#     restart: unless-stopped

# docker compose up -d    ← recreates the container, applies the policy
# docker compose restart  ← only restarts the existing container, policy unchanged


# ============================================
# PART 9: INSPECTING THE RESTART POLICY
# ============================================

# Check the policy and restart count.

docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' nginx-always
# always

docker inspect -f '{{.RestartCount}}' nginx-always
# 3


# ============================================
# PART 10: THE DECISION MATRIX
# ============================================

# no              → batch jobs, dev, interactive
# on-failure:5    → workers that should retry but not loop forever
# always          → services that must never be down
# unless-stopped  → most production services (respects manual stops)

The ten parts show the default, on-failure, always, unless-stopped, the on-failure reboot trap, the backoff sequence, docker update, the Compose restart gotcha, inspection commands, and the decision matrix.


Quick Reference

The Four Policies

PolicyRestart on failure?Restart on clean exit?Survive daemon restart?Respect manual stop?
noNoNoNoN/A
on-failureYesNoNoN/A
alwaysYesYesYesNo
unless-stoppedYesYesYesYes

Restart Backoff

AttemptDelay
1Immediate / 100ms
2200ms
3400ms
4800ms
…Doubles, max 1 minute

The backoff resets after 10 seconds of successful running .

Compose vs Swarm

EnvironmentKeyExample
Composerestart:restart: unless-stopped
Swarmdeploy.restart_policy:condition: on-failure

Common Commands

CommandPurpose
docker run --restart <policy>Set policy at creation
docker update --restart <policy>Change policy on running container
docker inspect -f '{{.HostConfig.RestartPolicy.Name}}'Check policy
docker inspect -f '{{.RestartCount}}'Check restart count

Best Practices

✅ Do This:

# Use unless-stopped for most production services
restart: unless-stopped                                                   # ✅
# Use on-failure with a limit for workers
restart: on-failure:5                                                     # ✅
# Recreate containers after changing the policy in Compose
docker compose up -d                                                      # ✅
# Set a policy for every long-running service
restart: unless-stopped                                                   # ✅

❌ Don’t Do This:

# Don't use on-failure for services that must survive reboots
restart: on-failure                                                       # ❌
# Don't expect restart: to change without recreating
docker compose restart                                                    # ❌
# Don't use always if you want manual stops to persist
restart: always                                                           # ❌
# Don't combine restart policies with host process managers
# (Docker warns against this)                                              # ❌
# Don't assume restart policies react to health status
restart: unless-stopped  # does NOT heal unhealthy containers             # ❌

Common Pitfalls

PitfallWhy It HappensFix
on-failure doesn’t survive rebootDaemon stops container cleanlyUse unless-stopped for long-running services
Policy change doesn’t take effectdocker compose restart doesn’t recreateUse docker compose up -d
Container restarts after manual stopalways ignores manual stopsUse unless-stopped
Restart loop consumes resourcesBroken container restarts repeatedlyBackoff limits it; fix the underlying issue
docker exec fails during restartContainer is in Restarting stateWait for it to stabilize
Policy ignored on first launchContainer must run 10s to “start successfully”Check that the container stays up
Swarm ignores restart:Swarm uses restart_policyUse deploy.restart_policy

Real-World Examples

1. Production Web Server

restart: unless-stopped

2. Worker with Retry Limit

restart: on-failure:5

3. Database

restart: unless-stopped

4. Batch Job

restart: "no"

5. Critical Service

restart: always

6. Change Policy on Running Container

docker update --restart unless-stopped mycontainer

7. Inspect Policy

docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' mycontainer

8. Swarm Restart Policy

deploy:
  restart_policy:
    condition: on-failure

9. Backoff Observation

docker logs -f crashing-container

10. Compose Recreate

docker compose up -d

Visual

The Policy Decision Flow

┌──────────────────────────────────────────────────────────────┐
│  POLICY DECISION FLOW                                        │
│                                                              │
│  Container exits                                             │
│    │                                                         │
│    ├── exit code 0 ──► on-failure: STAYS STOPPED             │
│    │                   always: RESTARTS                      │
│    │                   unless-stopped: RESTARTS              │
│    │                                                         │
│    └── exit code ≠ 0 ─► on-failure: RESTARTS                 │
│                         always: RESTARTS                     │
│                         unless-stopped: RESTARTS             │
│                                                              │
│  Daemon restarts                                             │
│    │                                                         │
│    ├── container was running ──► always: RESTARTS            │
│    │                             unless-stopped: RESTARTS    │
│    │                             on-failure: STAYS STOPPED   │
│    │                                                         │
│    └── container was stopped ──► always: RESTARTS            │
│                                  unless-stopped: STAYS       │
│                                  on-failure: STAYS STOPPED   │
│                                                              │
└──────────────────────────────────────────────────────────────┘

The always vs unless-stopped Distinction

┌──────────────────────────────────────────────────────────────┐
│  always vs unless-stopped                                    │
│                                                              │
│  Sequence: docker stop, then daemon restart                  │
│                                                              │
│  always:                                                     │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  docker stop app      → container stopped            │    │
│  │  reboot                → daemon starts               │    │
│  │  daemon checks         → app RESTARTS                │    │
│  │                                                       │    │
│  │  The manual stop is forgotten.                       │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  unless-stopped:                                             │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  docker stop app      → container stopped            │    │
│  │  reboot                → daemon starts               │    │
│  │  daemon checks         → app STAYS STOPPED           │    │
│  │                                                       │    │
│  │  The manual stop is respected.                       │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  This is the only behavioral difference between them.        │
│                                                              │
└──────────────────────────────────────────────────────────────┘

The on-failure Reboot Trap

┌──────────────────────────────────────────────────────────────┐
│  THE ON-FAILURE REBOOT TRAP                                  │
│                                                              │
│  Container running with restart: on-failure                  │
│    │                                                         │
│    │  Reboot initiated                                       │
│    ▼                                                         │
│  systemd stops docker.service                                │
│    │                                                         │
│    ▼                                                         │
│  daemon stops container with SIGTERM                         │
│    │                                                         │
│    ▼                                                         │
│  container exits with code 0 (clean stop)                    │
│    │                                                         │
│    ▼                                                         │
│  on-failure sees exit code 0 → no failure → no restart       │
│    │                                                         │
│    ▼                                                         │
│  daemon starts after reboot                                  │
│    │                                                         │
│    ▼                                                         │
│  on-failure container is NOT in the restart list             │
│    │                                                         │
│    ▼                                                         │
│  Container stays in Exited (0) state                         │
│                                                              │
│  The policy works as designed. The design is not what        │
│  most people expect for long-running services.               │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Exponential Backoff

┌──────────────────────────────────────────────────────────────┐
│  EXPONENTIAL BACKOFF                                         │
│                                                              │
│  Restart 1:  ── 100ms ──►                                    │
│  Restart 2:  ──── 200ms ────►                                │
│  Restart 3:  ──────── 400ms ────────►                        │
│  Restart 4:  ──────────────── 800ms ────────────────►        │
│  Restart 5:  ──────────────────────── 1600ms ────────►       │
│  ...                                                         │
│  Restart N:  ──────────────────────────────────── 1 min ──►  │
│                                                              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  The backoff resets after the container runs         │    │
│  │  successfully for 10 seconds.                        │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  This prevents a crashing container from consuming           │
│  the host's resources with rapid restart attempts.           │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
noNever restarts (default)
on-failure[:max]Restarts only on non-zero exit
alwaysRestarts on any exit; survives daemon restart; ignores manual stops
unless-stoppedLike always but respects manual stops
Backoff100ms, 200ms, 400ms, … up to 1 min
Backoff resetAfter 10 seconds of successful running
Compose keyrestart:
Swarm keydeploy.restart_policy:
Health statusRestart policies do not react to it

Key takeaways:

  • Restart policies react to process exit, not health status. An unhealthy-but-running container is never restarted by any policy. Health-based auto-healing requires a separate mechanism .
  • on-failure does not survive a daemon restart. A system reboot or Docker upgrade stops the container cleanly, and the policy sees no failure. For services that must survive reboots, use unless-stopped or always .
  • unless-stopped is the safest default for production. It restarts on crashes and daemon restarts but respects a manual docker stop. always ignores manual stops and brings the container back on the next daemon restart .
  • The difference between always and unless-stopped only appears after a manual stop followed by a daemon restart. In all other scenarios, they behave identically .
  • Docker applies an exponential backoff to restarts. The delay doubles from 100ms up to a maximum of one minute. The backoff resets after the container runs successfully for 10 seconds .
  • The restart policy is stored in the container, not the YAML file. Changing restart: in compose.yaml requires docker compose up -d to recreate the container. docker compose restart only restarts the existing container and does not apply the new policy .
  • Swarm ignores the Compose restart: key. Swarm uses deploy.restart_policy with condition, delay, max_attempts, and window options .
  • A container must run for at least 10 seconds to be considered “successfully started.” This prevents a container that fails immediately from entering a restart loop on first launch .

Remember: Restart policies are a safety net for process failures, not a health management system. They answer a single question: should this container be running after it exits? on-failure says “only if it failed,” but it does not survive reboots. always says “yes, no matter what,” but it ignores manual stops. unless-stopped says “yes, unless someone explicitly stopped it.” For most production services, unless-stopped is the correct choice because it recovers from crashes and daemon restarts while respecting the operator’s decision to stop a container. The policy is stored in the container, not the Compose file, so changing it requires recreating the container. And it has nothing to do with health status — an unhealthy container that is still running will never be restarted by a restart policy.


Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!