Restart Policies
Restart policies tell Docker to automatically restart a container if it crashes or when the daemon starts.
Syntax
docker run --restart=unless-stopped IMAGEBy default a stopped container stays stopped. A restart policy tells Docker to bring it back automatically, which is important for long-running services.
The available policies
no— never restart (the default).on-failure[:N]— restart only if it exits with an error, optionally up to N times.always— always restart, and start on daemon boot.unless-stopped— like always, but respects a manual stop.
Set the policy with the --restart flag when you run the container.
Example
# Restart automatically unless you stop it manually
docker run -d --restart=unless-stopped --name web nginx
# Retry up to 5 times only on failure
docker run -d --restart=on-failure:5 myworker:1.0
# Change the policy on an existing container
docker update --restart=always webWhen to use it
- A production service uses restart policy unless-stopped so it restarts after a crash but stays stopped if an operator manually halts it.
- A one-shot batch job uses restart policy on-failure:3 so it retries up to three times on failure before giving up.
- A developer avoids restart policies in local development so stopped containers stay stopped while they fix code.
More examples
Run with always-restart policy
Restarts the container automatically on any exit, including after the Docker daemon itself restarts.
docker run -d \
--name api \
--restart always \
-p 3000:3000 \
myapp:latestRetry on failure with limit
Restarts the container on non-zero exit codes up to 5 times, then stops retrying to avoid infinite crash loops.
docker run -d \
--name worker \
--restart on-failure:5 \
myworker:latestUpdate restart policy on running container
Changes the restart policy of an already-running container without needing to stop and recreate it.
# Change policy without recreating the container
docker update --restart unless-stopped myapp
# Verify the new policy
docker inspect myapp --format '{{.HostConfig.RestartPolicy.Name}}'
Discussion