Container restart policies
- Version
- 29
- Review
- Draft
Summary#
--restart on-failure retries nonzero exits. Add a positive limit, such as on-failure:3, to cap the retries. always restarts a stopped container when the daemon comes back, even after a manual stop. unless-stopped keeps a manually stopped container stopped across daemon restarts.
Syntax#
docker run --detach --restart on-failure:3 IMAGE
docker run --detach --restart unless-stopped IMAGE
docker update --restart unless-stopped CONTAINER
docker restart CONTAINER
Example#
The example uses a local alpine:3 image.
(
set -eu
name="dlr-docker-commands-restart-$$"
trap 'docker rm -f "$name" >/dev/null 2>&1 || true' EXIT
docker run --pull never --detach --name "$name" --restart on-failure:2 \
alpine:3 sh -c 'exit 7' >/dev/null
tries=0
until [ "$(docker inspect --format '{{.State.Status}} {{.RestartCount}}' "$name")" = "exited 2" ]; do
tries=$((tries + 1))
[ "$tries" -lt 30 ]
sleep 1
done
docker inspect --format 'state={{.State.Status}} exit={{.State.ExitCode}} restarts={{.RestartCount}}' "$name"
)
Expected output#
state=exited exit=7 restarts=2
Common mistakes#
--rm and a restart policy conflict. Engine restart policies react to process exits. If a health check fails while the main process keeps running, the policy leaves the container running.
Version applicability#
Checked with Docker Engine 29 for standalone containers. Swarm services have their own restart policy settings.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0