A restart policy decides what happens when a container’s process exits. It is a small setting with large consequences: the wrong choice leaves a service down, or hides a crash loop by restarting forever without fixing the cause.
Before you start
You should be comfortable with docker run and the container lifecycle. This article covers restart policies and their interaction with health checks.
Step-by-step walkthrough
Step 1: Match the policy to the failure you expect
no never restarts; on-failure restarts only when the exit code is non-zero; always restarts regardless of exit code; unless-stopped is like always but respects a manual stop. A long-running service typically wants unless-stopped; a batch job wants on-failure or no.
Step 2: Let the policy use backoff
Docker backs off restarts, so a crash loop does not spin at full speed. But a persistent failure still restarts indefinitely, which can hide a bug and keep a broken service “up” in name only. Surface the restart count so the loop is visible.
Step 3: Combine with health checks
A restart policy reacts to process exit, not to a process that is running but unhealthy. A HEALTHCHECK lets the orchestrator mark a hung container unhealthy and, with an external supervisor, restart it. Use both so hangs and crashes are each covered.
Worked scenario
A service restarts unless intentionally stopped.
docker run -d --restart unless-stopped --name api api-imageWalk through the example
If the API crashes, Docker restarts it, and if the host reboots, it comes back unless someone stopped it. on-failure would restart only on a non-zero exit, which is right for a job that should not rerun on success. The policy encodes the expected lifecycle.
Common mistake
Using always for everything, so a container with a permanent configuration error restarts forever and looks healthy while serving nothing. Another is relying on restarts instead of a health check, so a hung process is never recovered.
Verify the behavior
Kill the container’s process and confirm the policy restarts it. Stop it manually and confirm unless-stopped does not restart it. Introduce a config error and watch the restart count climb, showing the crash loop.
Interview exercise
When is on-failure better than always?
Answer and reasoning
When the container is a task that should run to completion: on-failure reruns it if it fails but leaves it stopped after success, preventing an endless loop of successful runs. always suits a long-running service that should be up whenever the host is. The exit semantics of the workload decide the policy.
Continue learning
Compare liveness in Docker healthchecks and shutdown in Docker signal handling. Read the Docker restart policies documentation and try the Docker interview questions.