You are currently viewing A Comprehensive Guide to Docker Restart Policy

A Comprehensive Guide to Docker Restart Policy

Docker has a restart policy option that enables your containers to restart themselves automatically in the event that specific events or failures occur at the container level. Doing this is very helpful if you need to restart the Docker host or if the service inside the container stops working.

When using Docker Compose or orchestrators like Docker Swarm and Kubernetes, you can define restart policies directly in your container configuration files using YAML. This allows you to set specific behaviors for each container individually. The flexibility of the Docker restart policy is particularly valuable in scenarios where service reliability and automated recovery are paramount. Whether your containers are part of a critical production service or a one-time task, you can tailor their restart behavior to suit your application’s needs.

Docker has transformed the landscape of application deployment and management through containerization. A crucial element of managing containers is ensuring that they can automatically recover in the event of failures or when intentionally stopped. Docker restart policies play a critical role in achieving these goals.

As a part of our significant service which is the Docker consulting service, we made this blog for you. With this guide, we will delve into Docker restart policy, explaining what they are, why they matter, and how to use them effectively. Read the whole blog, to get a better understanding and to set up Docker Restart Policies effectively.

Understanding Docker Restart Policies

Docker restart policies define the container’s behavior when it exits or crashes. They determine whether a container should be automatically restarted and under what conditions. These policies are crucial for maintaining the availability and resilience of containerized applications. Restart policies in Docker are like contingency plans for your containers. They determine when and how containers should automatically restart to ensure your services keep running smoothly.

To avoid excessive restarting, Docker has a safety mechanism in place. Restart policies only kick in if a container manages to run for at least 10 seconds without encountering a failure. This prevents your containers from getting stuck in an endless restart loop. It’s worth noting that if you manually stop a container, Docker won’t follow the restart policy for that specific instance. This precaution prevents containers from resuming their automatic restart cycles after being intentionally stopped.

Read more: Our Blog Post On crashloopbackoff kubernetes

Why Are Docker Restart Policies Important?

Docker restart policies help achieve this by ensuring that containers automatically recover from failures, reducing downtime and manual intervention. They are especially valuable in a clustered environment where multiple containers run together.

Docker restart policies are important because they help ensure that your containers stay up and running, even when unexpected issues or failures occur. They act like a safety net for your services, making sure they automatically recover when something goes wrong.

Imagine you have a critical application running in a container. If that container crashes or encounters an issue, a docker restart policy can automatically bring it back to life without manual intervention. This ensures that your services remain available and your applications keep working as expected.

So, Docker restart policies are crucial for maintaining the reliability and stability of your containerized applications. They save you time and effort by automating the recovery process and reducing downtime.

Types of Docker Restart Policy

Docker offers four restart policies, each designed for specific use cases:

a. “no”

Containers with this policy won’t be restarted automatically, regardless of the exit status.

Use when you want full control over container lifecycles.

b. “always”

Containers with this policy are always restarted, even if they exited gracefully.

Ideal for critical services that should run continuously.

c. “on-failure”

Containers with this policy are restarted only if they exit with a non-zero status code.

Suitable for applications that may encounter occasional failures.

d. “unless-stopped”

Containers with this policy are restarted unless explicitly stopped by the user. Useful for long-running background tasks.

Example

Let’s see an example of how to set a Docker restart policy using Docker’s command line interface (CLI) for a single container:

docker run --restart always my-service

In the example, the “my-service” container will always restart if it stops running unexpectedly. But if you manually stop the container, the Docker restart policy will only apply when the Docker daemon restarts or when you use a specific restart command.

The above example shows how you can configure a strategy to automatically restart a single container. However, when you’re working with multiple containers, Docker Compose comes in handy. It allows you to set docker restart policy for managing several containers, and you can do this using properties like “restart” or “restart_policy” in either normal or swarm mode.

Reason of Containers Stopped

If you’re wondering why a container has stopped, you can check its status by running the command docker ps -a. This command provides a list of all your containers, both running and stopped. Locate the container you’re interested in and check its “Status” column. For containers that have stopped, you’ll see an exit code displayed in brackets. If this code is greater than zero, it indicates that the container terminated due to an error.

To understand the specific reason for the error, you may need to refer to the documentation of the process running within the container. However, you can often gain insights into what caused the container to crash by examining its logs. Fortunately, logs are still available even after a container has stopped.

docker logs my-container

The log stream contains a compilation of the container’s standard output and standard error streams. If an error has been logged, you can typically find it in the last few lines of the log output. This information can be valuable in diagnosing and addressing the issue that led to the container’s termination.

Setup

Before we delve into implementing restart policies using Docker Compose, let’s prepare our working environment.

To test the docker restart policy we’re going to define, we need a running Docker container. For this, we’ll use a project from a previous article called “spring-cloud-docker,” which is a Dockerized Spring Boot application. This project comprises two Docker services that we will use to implement different restart strategies with Docker Compose.

First, let’s ensure that we can run both containers by running the following command from the project’s root directory:

docker-compose up --detach --build

Now, to confirm that both services are up and running, execute the following command:

docker-compose ps

You should see the two services listed as “Up,” and you can access them in your browser by visiting localhost:18888 and localhost:19999 to verify that the application services are functioning.

Defining Docker Restart Policies in Docker Compose 

Just like the Docker command for restarting containers, Docker Compose offers a way to automatically restart containers using the restart property.

You can set Docker restart policy in Docker Compose by adding the restart property to the service configuration in the docker-compose.yml file. Docker Compose uses the same values as the Docker CLI’s restart command to specify the restart strategy.

Now, let’s create docker restart policy for our containers. In the spring-cloud-docker project, we’ll need to modify the docker-compose.yml configuration file by adding the docker restart policy property:

message-server:
    container_name: message-server
    build:
        context: docker-message-server
        dockerfile: Dockerfile
    image: message-server:latest
    ports:
        - 18888:8888
    networks:
        - spring-cloud-network
    restart: no
product-server:
    container_name: product-server
    build:
        context: docker-product-server
        dockerfile: Dockerfile
    image: product-server:latest
    ports:
        - 19999:9999
    networks:
        - spring-cloud-network
    restart: on-failure

Notice how we added the restart property to both services. In this example, the message-server will not restart automatically (restart: no). In contrast, the product-server will only restart if it exits with a non-zero code, as specified by restart: on-failure.

Next, let’s explore how these policies are declared using Docker Compose in swarm mode.

Check Out: Our blog post on how to install docker on mac

Defining Restart Policies in Docker Compose Swarm Mode

Docker Compose in swarm mode offers a more extensive set of options for defining automatic container restart policies. However, this implementation works with Docker Compose v3, which introduces the deploy key-value pair in the configuration.

Here, we will explore the different properties to enhance the configuration for docker restart policy in swarm mode:

  • condition: Options include none, on-failure, or any (default).
  • delay: Represents the duration between restart attempts.
  • max_attempts: Indicates the maximum number of restart attempts outside of the restart window.
  • window: Refers to the duration used to determine if a restart is considered successful.

Now, let’s define our docker restart policy. First, ensure you’re using Docker Compose v3 by changing the version property to ‘3’:

version: '3'

Once you’ve updated the version, you can add the restart_policy property to your services. Just like in the previous section, we’ll make our message-server container restart automatically by setting the condition to any:

deploy:
    restart_policy:
        condition: any
        delay: 5s
        max_attempts: 3
        window: 120s

Similarly, we’ll define an on-failure docker restart policy for the product-server:

deploy:
    restart_policy:
        condition: on-failure
        delay: 3s
        max_attempts: 5
        window: 60s

Take note that the restart_policy property is within the deploy key. This indicates that restart policies are a part of the deployment configuration provided for managing a cluster of containers in swarm mode.

Additionally, both docker restart policies include extra configuration metadata to create a more robust restart strategy for the containers.

Conclusion

In this article, we’ve covered the concept of defining restart policies using Docker Compose. We started by introducing Docker restart policy and then applied them to a previous Baeldung project to illustrate two methods for configuring restart strategies for containers.
The first approach involved using the Docker Compose restart property configuration, which aligns with the options provided by the native restart command in the Docker CLI. The second method introduced the restart_policy property, which is exclusive to swarm mode and Docker Compose version 3. This approach allowed us to incorporate additional configuration values to fine-tune our restart policies.

FAQs

Q1. What is a Docker Restart Policy?

Docker Restart Policy defines how a Docker container behaves when it exits or crashes, determining whether and under what conditions the container should automatically restart.

Q2. Why are Docker Restart Policies important?

Docker Restart Policies are crucial for maintaining service availability. They automate container recovery, reducing downtime and manual intervention, especially valuable in clustered environments.

Q3. How can I set a Docker Restart Policy using the CLI?

Use the docker run –restart flag followed by the desired policy, like always or on-failure. For example: docker run –restart always my-service.

Q4. What does the “no” restart policy mean?

The “no” restart policy means the container won’t restart automatically, providing full control over its lifecycle. It’s useful when manual intervention is preferred.

Q5. When is the “always” restart policy useful?

The “always” restart policy is useful for critical services, ensuring they restart indefinitely even after graceful exits. Ideal for services requiring continuous operation.

Q6. How does the “on-failure” restart policy work?

The “on-failure” policy restarts the container only if it exits with a non-zero status. Customize it by specifying conditions like maximum attempts and delay between attempts.