Docker Restart Policies Explained
Understanding Docker restart policies is crucial for maintaining container uptime and ensuring that services recover from failures automatically. Docker provides several restart policies that determine how Docker should handle a container’s lifecycle events. This article breaks down these policies and guides you on when to use each.
Docker Restart Policies Explained
Docker’s restart policies provide control over how your containers behave in the event of a crash or when Docker restarts. Here’s what each policy means:
“no”
This policy is the default setting. With the no
restart policy, Docker does nothing if a container stops or crashes.
docker run --restart=no [IMAGE]
“always”
When you set a container’s restart policy to always
, Docker attempts to restart the container every time it stops, regardless of the reason.
docker run --restart=always [IMAGE]
“on-failure”
The on-failure
policy instructs Docker to restart the container only if it exits with an error code (non-zero exit status).
docker run --restart=on-failure [IMAGE]
“unless-stopped”
The unless-stopped
policy tells Docker to keep restarting the container until a developer forcibly stops it. It's similar to always
, but it respects intentional stops.
docker run --restart=unless-stopped [IMAGE]
Choosing the Right Restart Policy
Here are some considerations for choosing the right restart policy:
- Development vs. Production: In a development environment, you might prefer
no
to debug issues, while in production,always
oron-failure
could be more appropriate. - Stateless vs. Stateful Containers: Stateless containers can often use
always
, but stateful containers might need a more nuanced approach likeon-failure
. - Dependent Services: For containers that depend on other services,
on-failure
ensures they don't restart in a loop if a dependency is unavailable.
Best Practices
- Monitor Your Containers: Regardless of the restart policy, monitor your containers to understand their behavior and performance.
- Use Orchestrators for More Control: Tools like Docker Swarm or Kubernetes offer more sophisticated restart policies and orchestration.
- Graceful Shutdowns: Ensure your containers can handle
SIGTERM
for graceful shutdowns, especially when usingalways
orunless-stopped
.