Understanding unless-stopped vs always in Docker
When working with Docker, setting the right restart policy is crucial to ensure your services behave as expected, especially after a crash, system reboot, or manual intervention. Docker offers several restart policies, and two of the most commonly used are unless-stopped
and always
. Here’s a breakdown of the differences between them with an example using MongoDB in docker-compose.yml
.
unless-stopped
Policy
The unless-stopped
restart policy ensures that a container will automatically restart if it crashes or if the Docker daemon is restarted. However, it will not restart the container if it was manually stopped. This gives you control to keep a container stopped even after a system reboot or Docker daemon restart.
1 2 3 4 5 6 7 8 9 10 |
version: '3' services: mongodb: image: mongo container_name: my_mongodb ports: - "27017:27017" restart: unless-stopped |
In this example, MongoDB will restart automatically if it crashes or if the system reboots, but if you stop the container manually with docker stop my_mongodb
, Docker will not restart it again until you explicitly run docker start my_mongodb
.
always
Policy
The always
restart policy guarantees that the container will always restart, even if it was manually stopped. This policy ensures that the container is running at all times, making it useful for services that you want to continuously operate without manual intervention.
1 2 3 4 5 6 7 8 9 10 |
version: '3' services: mongodb: image: mongo container_name: my_mongodb ports: - "27017:27017" restart: always |
In this example, MongoDB will automatically restart if it crashes, the Docker daemon is restarted, or the system reboots. Even if you manually stop the container with docker stop my_mongodb
, Docker will attempt to restart it, ensuring it’s always running.
Key Differences:
unless-stopped
: The container will restart after crashes or system reboots but will remain stopped if manually stopped by the user.always
: The container will restart in all circumstances, even after being manually stopped.
Which Policy Should You Use?
- Use
unless-stopped
if you want to retain control over containers that you manually stop, such as for debugging or maintenance purposes. - Use
always
if you want the container to run continuously and automatically restart regardless of how it was stopped, ensuring uptime for critical services.
By choosing the right restart policy, you can ensure that your MongoDB instance—or any other service running in Docker—behaves exactly as intended, minimizing downtime and manual interventions.
It’s clear my concept