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: Likealways, 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-failurewithout specifying max retries, which may cause endless restarts on persistent failures. - Expecting
noto restart containers automatically (it does not). - Not understanding that
unless-stoppedwill not restart containers stopped manually, unlikealways.
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 Policy | Description |
|---|---|
| no | Do not restart automatically (default) |
| on-failure[:max-retries] | Restart only on failure, optionally limit retries |
| always | Always restart container if it stops |
| unless-stopped | Restart 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.