BudiBadu Logo
Samplebadu

Docker Compose by Example: Restart Policies

Compose Specification v2

Configuring container restart behavior with this sample code demonstrating no restart default, on-failure for error-only restarts, always for aggressive restarts, and unless-stopped respecting manual stops.

Code

services:
  # 1. Default (no restart)
  job:
    image: my-batch-job
    restart: "no"
    
  # 2. Restart if exit code != 0
  api:
    image: my-api
    restart: on-failure
    
  # 3. Always restart (even if manually stopped, on daemon restart)
  db:
    image: postgres:15
    restart: always
    
  # 4. Unless stopped (don't restart if manually stopped)
  worker:
    image: my-worker
    restart: unless-stopped

Explanation

Restart policies instruct the Docker daemon how to handle container exits, essential for production reliability and automatic recovery from crashes or server reboots. The default policy "no" means containers won't restart automatically, suitable for one-time jobs or tasks expected to complete and exit.

The always policy provides the most aggressive restart behavior, restarting containers regardless of exit codes. Manually stopped containers restart when the Docker daemon restarts, ensuring maximum availability. The unless-stopped policy is similar but respects manual stop commands, preventing restart on daemon boot if explicitly stopped beforehand, useful for services requiring manual intervention.

The on-failure policy only restarts containers exiting with non-zero exit codes indicating errors. This prevents Docker from endlessly restarting batch jobs or scripts that completed successfully with exit code 0. This policy is ideal for tasks expected to finish, like data processing jobs or migration scripts, where successful completion should not trigger restarts.

Code Breakdown

5
restart: "no" default policy, no automatic restart on exit.
10
restart: on-failure restarts only on error exit codes, not on clean exit 0.
15
restart: always ensures high availability, restarts regardless of exit code or manual stop.
19
restart: unless-stopped respects manual stops, won't restart if explicitly stopped.