0
0
DockerHow-ToBeginner · 3 min read

How to Set Restart Policy for Docker Container

Use the --restart flag with docker run to set a container's restart policy. For example, docker run --restart=always restarts the container automatically if it stops or the system reboots.
📐

Syntax

The --restart option in docker run sets the restart policy for a container. It controls when Docker restarts the container automatically.

  • no: Do not restart the container automatically (default).
  • on-failure[:max-retries]: Restart only if the container exits with a failure code. Optionally limit retries.
  • always: Always restart the container if it stops.
  • unless-stopped: Like always, but does not restart if the container was stopped manually.
bash
docker run --restart=<policy> [OPTIONS] IMAGE [COMMAND] [ARG...]
💻

Example

This example runs an Nginx container with the restart policy set to always. The container will restart automatically if it stops or the Docker daemon restarts.

bash
docker run -d --name mynginx --restart=always nginx
Output
a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6
⚠️

Common Pitfalls

Common mistakes when setting restart policies include:

  • Using --restart=on-failure without specifying max retries, which may cause endless restarts on persistent failures.
  • Expecting no to restart containers automatically (it does not).
  • Not understanding that unless-stopped will not restart containers stopped manually, unlike always.
bash
docker run -d --name badcontainer --restart=no nginx
# This container will NOT restart automatically

docker run -d --name goodcontainer --restart=on-failure:3 nginx
# This container restarts up to 3 times on failure
📊

Quick Reference

Restart PolicyDescription
noDo not restart automatically (default)
on-failure[:max-retries]Restart only on failure, optionally limit retries
alwaysAlways restart container if it stops
unless-stoppedRestart always except when stopped manually

Key Takeaways

Use the --restart flag with docker run to control container restart behavior.
The 'always' policy restarts containers on any stop or system reboot.
'on-failure' restarts only on errors and can limit retry attempts.
'unless-stopped' prevents restart if container was stopped manually.
Default policy 'no' means no automatic restarts.