Docker restart policies are there to keep containers active in all possible downfalls, we can leverage it in multiple ways as an example if we have a web server running on a container and have to keep it active even on bad request we can use unless-stopped
flag, it will keep the server up and running till we stopped it manually.
Restart flag can be any one of these :-
"no"
:- it is the default value, and it will never restart the container.
on-failure
:- it will restart the container whenever it encounters an error, or say, whenever the process running inside the container exit with non-zero exit code. Exit code :- 0 means no error, we terminated the process intentionally, but any non-zero value is an error.
always
:- as the name, it will always restart the container, no matter whatever be the exit code is. Also, it will restart the container even when we manually stopped it but for that we need to restart the docker daemon.
unless-stopped
:- it is similar to the always
flag the only difference is once the container is stopped manually it will not restart automatically even after restarting the docker daemon, until we start the container manually again.
The difference between unless-stopped
and on-failure
is the first will always restart until we stopped it manually no matter whatever be the exit code will be and another will only restart the container on real failure, i.e. exit code = non-zero.
Once the container is stopped its restart flags are ignored, this is one way to overcome from restarting loop. That's why in the case of always
flag once we stopped it manually the container will not restart till we restart the docker daemon.
You can easily test all of these flags by creating a simple redis-server:
docker run -d --restart=always --name redis-server redis # start redis image
docker container ls # test the status
docker stop redis-server # stop the container manually
docker container ls # test the status again, got the redis-server did not restarted
sudo service docker restart # restart the docker daemon
# test the status again will find the container is again up and running
# try the same steps by changing the restart flag with *unless-stopped*
docker update --restart=unless-stopped redis-server # will update the restart flag of running container.