Docker Restart Policy
Docker restart policies help manage container lifecycle by automatically restarting containers when they exit. Here are the main differences between the
always
and on-failure
restart policies:2 minute read
always
Restart Policy
- Behavior: The container is always restarted, regardless of the exit status. It doesn’t matter if the container exited with an error or normally, Docker will restart it.
- Use Case: This policy is useful for services that need to be running continuously and should not be stopped for any reason. For example, web servers, databases, or any critical background services.
- Example: If you stop a container manually with
docker stop
ordocker kill
, it will still be restarted automatically.
on-failure
Restart Policy
- Behavior: The container is restarted only if it exits with a non-zero exit code (indicating an error). If the container exits successfully (with an exit code of 0), it will not be restarted.
- Use Case: This policy is useful for applications that should only restart if they fail due to an error but can be allowed to stop if they complete their task successfully. For example, batch jobs, data processing tasks, or short-lived services.
- Example: If you stop the container manually with
docker stop
ordocker kill
, it will not be restarted. Similarly, if the container exits successfully, it won’t be restarted either.
Example of Usage
You can set these restart policies using the --restart
flag with the docker run
command:
# `always` restart policy
docker run --restart always my-container
# `on-failure` restart policy
docker run --restart on-failure my-container
Feedback
Was this page helpful?
Glad to hear it!
Sorry to hear that.