Docker Container Restart Policies
It's often a good idea to run containers with a restart policy. This is a basic form of self-healing that allows the local Docker engine to automatically restart failed containers.
Restart policies are applied per container. They can be configured imperatively on the command line as part of docker run commands or declaratively in YAML files for use with higher-level tools such as Docker Swarm, Docker Compose, and Kubernetes.
In this document, we will get to know about the following restart policies:
- always
- unless-stopped
- on-failure
Restart Policies Explained
always
The always policy is the simplest. When a container has this restart policy, Docker will automatically restart the container if it stops or encounters an error.
The first process in the list, with PID 1, is the shell we told the container to run. The second process is the ps -elf command we ran to produce the list. This is a short-lived process that exits as soon as the output is displayed.
Type exit from the shell to kill the container's PID 1 process and stop the container. Docker will automatically restart it because it has the --restart always policy.
Check the container’s status:
docker ps
We should see that the container is running again.
You will see a output similar to this:
An interesting feature of the --restart always policy is that if we stop a container with docker stop and then restart the Docker daemon, the container will be restarted.
To illustrate:
Start a new container with the --restart always policy and intentionally stop it with the docker stop command.
The container will be in the Stopped (Exited) state.
Restart the Docker daemon, and the container will be automatically restarted when the daemon comes back up.
unless-stopped
The main difference between the always and unless-stopped policies is that containers with the --restart unless-stopped policy will not be restarted when the daemon restarts if they were in the Stopped (Exited) state.
Stop both containers:
docker stop always unless-stopped
Verify both containers are stopped:
docker ps -a
we will see output similar like this:
The always container has been restarted, but the unless-stopped container has not.
on-failure
The on-failure policy will restart a container if it exits with a non-zero exit code. It will also restart containers when the Docker daemon restarts, even those that were in the stopped state.
SOCIAL SHARE CARD GENERATOR