Configuring Container Restart Policies
Docker allows you to configure restart policies for containers. A restart policy determines whether a container should be automatically restarted by the Docker daemon after it exits. This is a crucial feature for ensuring the availability of your applications.
In this step, you will learn how to configure restart policies for Docker containers.
First, let's stop and remove the previous my-nginx
container to start fresh.
docker stop my-nginx
docker rm my-nginx
Now, let's run a new Nginx container with a restart policy of always
.
docker run -d --name my-nginx-always --restart=always -p 80:80 nginx
The --restart=always
flag tells Docker to always restart the container if it stops, regardless of the exit code. It will also restart the container when the Docker daemon starts.
Check that the container is running:
docker ps
Now, let's simulate a container failure by stopping it manually.
docker stop my-nginx-always
Wait a few seconds and then check the container status again:
docker ps
You should see that the my-nginx-always
container has been automatically restarted by the Docker daemon. The STATUS
column will indicate that it has been Up
for a short period.
Other common restart policies include:
no
: Do not automatically restart the container (default).
on-failure
: Restart the container only if it exits with a non-zero exit code (indicating an error). You can optionally specify the maximum number of restart attempts (e.g., on-failure:5
).
unless-stopped
: Always restart the container unless it is explicitly stopped by the user or the Docker daemon is stopped.
Let's try the on-failure
policy. Stop and remove the current container:
docker stop my-nginx-always
docker rm my-nginx-always
Run a new container with the on-failure
policy:
docker run -d --name my-nginx-on-failure --restart=on-failure -p 80:80 nginx
Check that it's running:
docker ps
Now, let's simulate a failure. We can do this by executing a command inside the container that exits with a non-zero status.
docker exec my-nginx-on-failure sh -c "exit 1"
Check the container status after a few seconds:
docker ps
The container should have been automatically restarted because it exited with a non-zero status.
Restart policies are a powerful tool for ensuring the resilience of your containerized applications. By configuring the appropriate policy, you can automate the recovery of containers that stop unexpectedly.