Restart policies in a Docker container

Reading Time: 3 minutes

To enable self-healing in a docker container, we can use restart policies in docker.

There are three restart policies:

  • on-failure
  • always
  • unless-stopped

on failure:

It restarts the docker container if the container exits because of some failure or exits with a non-zero exit code. It will also restart the container when the Docker daemon restarts even if the containers were in a stopped state.

always:

It will always restart the docker container unless it has been explicitly or manually stopped. If it is manually stopped via the docker container stop <container-name> command, it will get restarted after the docker daemon restarts.

Let us run an alpine container and set the restart policy as always via the command line.

docker container run --name mycontainer -it --restart always alpine sh


As we know, if we exit from this container, the container should automatically go to a stopped state.

Since the restart policy was set to always, docker will restart the container as soon as we exit from it. If you notice the difference between CREATED and STATUS fields, you would notice the difference.

Let us now stop this docker container.

docker container stop mycontainer

Check if there is any container running

There is no container running at the moment. So let’s restart docker.

systemctl restart docker

Check if the container restarted

docker ps

The container got restarted when we restarted the docker daemon as the restart policy was set to always.

unless-stopped

It is similar to always, but it does not restart the docker container after the docker daemon restarts.

This will restart the docker container if we exit from the container, similar to what the restart policy:always do. The only difference is that if we restart the docker daemon, the container will not spin up again.

docker update --restart unless-stopped myconatiner

docker container run --name mycontainer -it --restart unless-stopped alpine sh

It restarted the container after exiting it.

Let us stop the running container and see the container restart when we restart the docker daemon.

systemctl restart docker

The Docker container did not start with the docker daemon restart. This shows the difference between restart policies: always and unless-stopped.


Hey, readers! Thank you for sticking up till the end. If you have any questions/feedback regarding this blog, I am reachable at vidushi.bansal@knoldus.com. You can find more of my blogs here.

Written by 

Vidushi Bansal is a Software Consultant [Devops] at Knoldus Inc. She is passionate about learning and exploring new technologies.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading