6.2.1.5 Detached Restart Behavior
A focused guide to Detached Restart Behavior, connecting core concepts with practical Docker and container operations.
Detached restart behavior is governed by a container's configured restart policy, determining whether and how Docker automatically restarts a detached container if its main process exits unexpectedly, without requiring manual intervention from whoever originally started it.
Configuring a Restart Policy
A restart policy is specified at container creation time, controlling exactly when automatic restarts should occur.
docker run -d --restart=unless-stopped --name myapp myapp:1.0
With this policy, if myapp's main process crashes, Docker automatically restarts it; the policy is honored unless the container was explicitly stopped by an operator.
Available Restart Policy Options
Different policies suit different needs, ranging from never restarting automatically to always doing so regardless of circumstances.
docker run -d --restart=no myapp:1.0
docker run -d --restart=on-failure:3 myapp:1.0
docker run -d --restart=always myapp:1.0
docker run -d --restart=unless-stopped myapp:1.0
on-failure:3 restarts only on failure, up to three attempts; always restarts unconditionally, even after a deliberate stop, if the daemon itself restarts; unless-stopped behaves similarly but respects an explicit stop.
Why unless-stopped Is Often the Sensible Default
unless-stopped provides automatic recovery from crashes while still respecting a deliberate, explicit stop — avoiding the surprising behavior of always, where a container an operator intentionally stopped might unexpectedly restart anyway if the Docker daemon itself restarts.
docker run -d --restart=unless-stopped myapp:1.0
docker stop myapp
sudo systemctl restart docker
docker ps -a --filter "name=myapp"
The container remains stopped after the daemon restart, since it was explicitly stopped beforehand.
Why Detached Restart Behavior Matters
A correctly configured restart policy is essential for a detached service container to recover automatically from crashes without requiring manual intervention, while still behaving predictably and respecting deliberate operator actions like an explicit stop.