DEV Community

loading...
Cover image for How to restart containers automatically in docker

How to restart containers automatically in docker

ajeetht profile image Ajeeth thangarasu ・3 min read

If we are using docker containers for personal use we can restart it manually using docker restart. The docker restart command allow us to restart containers with some time limit. But, in production it is difficult to restart by manual. To restart containers automatically, we can use restart policies for docker containers.

This post was originally posted on developersdoors

Restart policies for docker containers

Restart polies allows the container to restart automatically in required situations. The situations may be when a failure occurs, when daemon starts, when a container stopped.
The --restart flag is used with docker run command when starting a container. There are four restart policies available.

no Do not automatically restart containers anyway
always Always restart the container even though the container stopped manually. Until the daemon stops or the restart policy is changed, it will restart it in loop.
on-failure Restart the container if it exits due to an error, which manifests as a non-zero exit code. If any container is stopped due to any fault, it will automatically restart those containers with this policy.
unless-stopped Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

To run a container with restart policies, try with following code pattern

docker run --restart no hello-world

The above command run the hello-world image with restart policy set as no. It will not restart the containers automatically.

docker update --restart always hello-world

Here I use update command to update the restart policy of the hello-world container with always policy. This will restart the container always even though it is stopped manually or start when the daemon starts.

To view the events that occurs during restart we can use event command.

docker event

Open the docker event in one shell and run the container with always policy with another shell. The event shows the hello-world container will restart automatically every times it stopped. The image shows that every time the hello-world container stopped, it restart it.

docker restart containers(1)

We can also restart the containers using process managers such as upstart, systemd, supervisor. I will be posting an article on using process managers for docker in later.

For any reference to docker -> go.

For my other docker archives -> go.

If you like the article feel free to share.

Discussion (1)

pic
Editor guide
Collapse
bobbyiliev profile image
Bobby Iliev

Thanks for sharing this!
I have a video in how to do that as well:

Restart docker container automatically