What are Docker Restart Policies (no, always, unless-stopped, on-failure)?
❓ Interview Prompt: Explain Docker container restart policies and when to use each for production reliability vs development flexibility.
Docker restart policies determine whether the Docker daemon automatically restarts a container when it exits, crashes, or the Docker daemon itself restarts.
Restart Policy Options:
| Policy | Behavior |
|---|---|
| no (default) | Never restart automatically. Container stays stopped. |
| always | Restart whenever container stops, regardless of exit code. Starts on Docker daemon boot. |
| unless-stopped | Like always, but does NOT restart if you manually stopped it with docker stop. |
| on-failure[:max-retries] | Restart only on non-zero exit codes. Optional retry limit. |
When to Use:
Code Implementation Example
# Production API — restart always (survives host reboots)
docker run -d \
--name api \
--restart always \
-p 3000:3000 \
myapp:latest
# Unless-stopped — restarts on crash/reboot, respects manual stop
docker run -d \
--name worker \
--restart unless-stopped \
myworker:latest
# On-failure with max 3 retries (batch job, prevents infinite crash loops)
docker run -d \
--name migration \
--restart on-failure:3 \
myapp:latest npm run migrate
# Update restart policy on a running container
docker update --restart always myapi
# Check restart count and policy
docker inspect myapi --format '{{.RestartCount}} restarts, policy: {{.HostConfig.RestartPolicy.Name}}'Use --restart always for production services to survive host reboots. Use --restart on-failure:3 for batch jobs to prevent infinite crash loops.