skip to content
clipboard

Docker Compose Restart Policy

Restart Policy Options

Docker Compose provides several restart policy options to control how containers are restarted when they exit or fail. These policies are set in your docker-compose.yml file under each service.

1. restart: unless-stopped

  • The container will always restart unless it is explicitly stopped by the user.
  • Useful for production environments where you want services to run continuously.

2. restart: on-failure

  • The container will restart only if it exits with a non-zero exit code (i.e., on failure).
  • You can optionally specify a maximum number of restart attempts.
  • Good for jobs or tasks that should retry on error but not run forever.

3. restart: always

  • The container will always restart, regardless of exit status.
  • Even after a Docker daemon restart, the container will be started again.
  • Suitable for critical services that must always be running.

4. restart: no (default)

  • The container will not be restarted automatically.
  • Best for development or one-off tasks.

Comparison Table

PolicyRestarts on FailureRestarts on StopRestarts on Docker RestartUse Case
noNoNoNoDevelopment, one-off
alwaysYesYesYesProduction, critical
unless-stoppedYesNo (if stopped)YesProduction, persistent
on-failureYesNoNoJobs, error recovery

Development vs Production Comparison

EnvironmentRecommended PolicyReasoningExample Use Case
Developmentno or on-failureAvoids unwanted restarts, easier debuggingTesting, local dev
Productionalways or unless-stoppedEnsures services stay running, high availabilityWeb server, API backend

Example Usage in docker-compose.yml

services:
  web:
    image: nginx
    restart: always

  worker:
    image: my-worker
    restart: on-failure:5

Best Practices

  • Use restart: always or restart: unless-stopped for long-running production services.
  • Use restart: on-failure for batch jobs or workers that should retry on error.
  • Avoid restart policies for development containers unless you need automatic recovery.
  • Explicitly stop containers when you want them to remain stopped with unless-stopped.

By understanding and configuring Docker Compose restart policies, you can ensure your containers behave reliably in both development and production environments.

Source: Notion Article