In this lesson, you will learn how to make your services self-healing by configuring restart policies to handle unexpected crashes or container exits automatically.
Why Restart Policies Matter
When running services in production, crashes are inevitable—whether due to a memory spike, a dependency failure, or an external process interruption. Without a restart policy, a container that exits will simply remain in a Stopped state, requiring you to manually intervene with docker start. By defining a restart policy, you instruct the Docker engine to monitor your container’s exit status and take action based on specific rules.
Configuring Policies in Docker Compose
You define these behaviors within your docker-compose.yml file using the restart key. Here are the most common options:
no: The default; the container will not restart automatically.always: The container will always restart if it stops, regardless of the exit code. This is ideal for core services that must remain available.on-failure: The container restarts only if it exits with a non-zero exit code (indicating an error).unless-stopped: The container restarts automatically unless you manually stop it usingdocker stop.
Here is a practical example of how to implement this in a service definition:
services:
web-api:
image: my-app:latest
restart: on-failure
ports:
- "8080:80"
When to Use Which?
Think of on-failure as a safety net for unstable code that might crash under specific conditions, whereas always is best for critical infrastructure components, like a reverse proxy or a database connector, that should be running as long as the Docker daemon is active.
Note that Docker applies these policies after the container has started successfully. If a container fails to start due to a configuration error (like an invalid command), Docker will not keep trying to restart it infinitely, as this would consume unnecessary system resources.
Key Takeaway: Restart policies eliminate the need for manual intervention by allowing the Docker daemon to automatically revive containers that exit unexpectedly, ensuring your services remain resilient.