Restart Policies and Inspection
Restart policies
Section titled “Restart policies”By default a container that stops or crashes stays stopped. Restart policies tell Docker when to restart it automatically.
| Policy | Behaviour |
|---|---|
no | Never restart (default). |
always | Always restart, even on manual docker stop. Starts on Docker daemon boot. |
unless-stopped | Restart automatically, but not if you stopped it manually. Starts on daemon boot unless it was stopped. |
on-failure[:N] | Restart only when the exit code is non-zero. Optional max retry count. |
# Recommended for long-running servicesdocker run -d --restart unless-stopped nginx:alpine
# Restart up to 5 times on failuredocker run -d --restart on-failure:5 myworker:latestInspecting a container
Section titled “Inspecting a container”docker inspect returns the full JSON configuration of a container — network settings, mounts, environment variables, restart policy, and more:
docker inspect webserverTo pull out a single field use --format with Go template syntax:
# Get the container's IP addressdocker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' webserver
# Get the restart policydocker inspect --format '{{.HostConfig.RestartPolicy.Name}}' webserverLive resource monitoring with docker stats
Section titled “Live resource monitoring with docker stats”docker stats shows a live, updating table of CPU, memory, network I/O, and disk I/O for running containers:
# All running containersdocker stats
# Specific container, one snapshot (no live update)docker stats --no-stream webserverCONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/Oa1b2c3d4e5f6 webserver 0.1% 5.2MiB / 7.62GiB 0.07% 1.2kB / 648B 0B / 0BResource limits
Section titled “Resource limits”Containers can consume all available memory and CPU if left unconstrained. Set limits at run time:
docker run -d \ --name limited \ --memory 256m \ --cpus 0.5 \ nginx:alpine--memory 256m— hard memory cap (container is OOM-killed if it exceeds this)--cpus 0.5— allow the container to use at most half a CPU core
Verify the limits are applied:
docker inspect --format '{{.HostConfig.Memory}}' limited# 268435456 (256 * 1024 * 1024 bytes)# 1. Run nginx with a restart policy
docker run -d --name webserver --restart unless-stopped nginx:alpine
# 2. Inspect the full config (JSON)
docker inspect webserver | head -60
# 3. Extract just the restart policy
docker inspect --format '{{.HostConfig.RestartPolicy.Name}}' webserver
# 4. Live stats (one snapshot)
docker stats --no-stream webserver
# 5. Run a memory-limited container
docker run -d --name limited --memory 128m --cpus 0.25 nginx:alpine
# 6. Confirm the memory limit
docker inspect --format '{{.HostConfig.Memory}}' limited
# 7. Clean up
docker stop webserver limited && docker rm webserver limited