0
0
DockerHow-ToBeginner · 3 min read

How to Use Restart Policy in Docker Compose for Reliable Containers

In Docker Compose, use the restart key under a service to define its restart policy, such as no, always, on-failure, or unless-stopped. This controls when Docker restarts containers automatically, helping keep your services running smoothly.
📐

Syntax

The restart policy is set inside a service definition in your docker-compose.yml file. It accepts these values:

  • no: Do not restart the container automatically (default).
  • always: Always restart the container if it stops.
  • on-failure: Restart only if the container exits with a non-zero status (failure).
  • unless-stopped: Restart always except when the container is explicitly stopped.
yaml
services:
  myservice:
    image: myimage
    restart: always
💻

Example

This example shows a simple docker-compose.yml file where a web service uses the restart: on-failure policy. It will restart the container only if it crashes or exits with an error.

yaml
version: '3.8'
services:
  web:
    image: nginx:alpine
    restart: on-failure
    ports:
      - "8080:80"
Output
docker-compose up -d Starting web ... done # If the container crashes, Docker restarts it automatically.
⚠️

Common Pitfalls

Common mistakes include:

  • Using restart: always without understanding it restarts even on manual stops, which can confuse debugging.
  • Not specifying a restart policy, so containers do not restart after failure.
  • Using on-failure without a max retry count, which can cause endless restarts if the container always fails.

Always choose the policy that fits your use case and monitor container behavior.

yaml
services:
  app:
    image: myapp
    restart: always  # This restarts even if you stop the container manually

# Better:
services:
  app:
    image: myapp
    restart: unless-stopped  # Stops restarting if you stop container manually
📊

Quick Reference

Restart PolicyDescriptionWhen to Use
noDo not restart container automaticallyFor one-time or manual containers
alwaysAlways restart container on exitFor critical services needing high availability
on-failureRestart only on failure exit codesFor apps that may crash and need retry
unless-stoppedRestart unless container stopped manuallyFor services you want running unless stopped

Key Takeaways

Use the restart key in docker-compose.yml under each service to set restart policies.
Choose the policy based on your service needs: always, on-failure, unless-stopped, or no.
Restart policies help keep containers running after crashes or system reboots.
Avoid always if you want to stop containers manually without automatic restart.
Monitor container restarts to avoid infinite loops with failing containers.