How to Use Restart Policy in Docker Compose for Reliable Containers
In Docker Compose, use the
restart key under a service to define its restart policy, such as no, always, on-failure, or unless-stopped. This controls when Docker restarts containers automatically, helping keep your services running smoothly.Syntax
The restart policy is set inside a service definition in your docker-compose.yml file. It accepts these values:
no: Do not restart the container automatically (default).always: Always restart the container if it stops.on-failure: Restart only if the container exits with a non-zero status (failure).unless-stopped: Restart always except when the container is explicitly stopped.
yaml
services:
myservice:
image: myimage
restart: alwaysExample
This example shows a simple docker-compose.yml file where a web service uses the restart: on-failure policy. It will restart the container only if it crashes or exits with an error.
yaml
version: '3.8' services: web: image: nginx:alpine restart: on-failure ports: - "8080:80"
Output
docker-compose up -d
Starting web ... done
# If the container crashes, Docker restarts it automatically.
Common Pitfalls
Common mistakes include:
- Using
restart: alwayswithout understanding it restarts even on manual stops, which can confuse debugging. - Not specifying a restart policy, so containers do not restart after failure.
- Using
on-failurewithout a max retry count, which can cause endless restarts if the container always fails.
Always choose the policy that fits your use case and monitor container behavior.
yaml
services:
app:
image: myapp
restart: always # This restarts even if you stop the container manually
# Better:
services:
app:
image: myapp
restart: unless-stopped # Stops restarting if you stop container manuallyQuick Reference
| Restart Policy | Description | When to Use |
|---|---|---|
| no | Do not restart container automatically | For one-time or manual containers |
| always | Always restart container on exit | For critical services needing high availability |
| on-failure | Restart only on failure exit codes | For apps that may crash and need retry |
| unless-stopped | Restart unless container stopped manually | For services you want running unless stopped |
Key Takeaways
Use the restart key in docker-compose.yml under each service to set restart policies.
Choose the policy based on your service needs: always, on-failure, unless-stopped, or no.
Restart policies help keep containers running after crashes or system reboots.
Avoid always if you want to stop containers manually without automatic restart.
Monitor container restarts to avoid infinite loops with failing containers.