On Linux systems, applications managed by systemd can be configured to start automatically on boot using systemctl enable. For Docker containers, the equivalent behavior is defined through the --restart flag when creating a container. The widely used option --restart unless-stopped is the key to automatic startup after a host reboot.
The docker run command provides a --restart parameter, as shown in its help output:
--restart string Restart policy to apply when a container exits (default "no")
Docker offers four restart policies, each suited for different scenarios:
| Policy | Description | Typical Use |
|---|---|---|
--restart=unless-stopped |
The container restarts after the Docker daemon reboots, unless it was manually stopped before the daemon went down. Containers that were running will be brought backup. | Common choice for general services. |
--restart=always |
The container is always restarted regardless of why it exited (including normal exit). | Critical services that must remain available. |
--restart=on-failure[:max-retry] |
The container restarts only if it exits with a non-zero exit code. An optional limit on retry attempts can be set. | Services that may fail due to transient errors and can self-recover. |
--restart=no |
The default policy. The container does not restart under any circumstances after exit. | One-off tasks or containers that should not persist. |
It's important to note that docker stop overrides the unless-stopped policy. For example, if you stop all containers manually with docker stop $(docker ps -aq) and then reboot the host, those containers will not restart — this behavior matches the semantics of unless-stopped.
To check the restart count of a container using the always policy, you can inspect it:
docker inspect --format '{{ .RestartCount }}' container_name
What if You Forgot to Set --restart?
You can update an existing container's restart policy without recreating it using docker update. For example:
docker update --restart=unless-stopped container_name
Seven Container States
| State | Meaning |
|---|---|
| created | The container has been created but not started. |
| running / Up | The container is actively running. |
| paused | The container's processes have been paused. |
| removing | The container is being removed (migration in progress). |
| restarting | The container is in the process of restarting. |
| exited | The container has stopped running. |
| dead | The container is in an unusable state. |
Container Exit Codes
You can view the exit code of a container using docker ps -a (under the STATUS column) or by inspecting the container:
docker inspect container_name
Look for the State.ExitCode field.
| Exit Code | Meaning |
|---|---|
| 0 | Normal or graceful exit. |
| Non-zero (e.g., 1, 125, 127) | Abnormal exit. Common causes: 1 indicates a runtime error, 125 often from a docker run failure, 127 means a command was not found inside the container. |