Running containers: lifecycle, resources and logs
Lifecycle
created → running → (paused) → exited → removed
docker run -d --name web -p 8080:80 nginx:1.27 # create + start, detached
docker run --rm -it alpine:3.20 sh # interactive, removed on exit
docker ps / docker ps -a # running / all
docker stop web # SIGTERM, then SIGKILL after 10 s (-t to change)
docker kill web # SIGKILL immediately
docker start -ai web
docker rm -f web
docker exec -it web sh # new process inside a running container
docker logs -f --tail 100 web
docker inspect web # full JSON: mounts, networks, env, state, exit code
docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' web
docker stats # live CPU/memory/net/IO per container
docker top web # processes in the container
docker cp web:/etc/nginx/nginx.conf .
docker events # daemon event stream
A container lives as long as its PID 1 lives. A container that "exits immediately" usually ran a command that finished, a daemon that forked into the background (e.g. nginx without daemon off;), or crashed — check docker logs and the exit code.
Restart policies
| Policy | Behaviour |
|---|---|
no (default) |
Never restart |
on-failure[:N] |
Restart on non-zero exit, optionally max N times |
always |
Restart whenever it stops; a manually stopped container comes back when the daemon (or host) restarts |
unless-stopped |
Like always, but a manually stopped container stays stopped even after a daemon restart |
Resource limits
docker run -m 512m --memory-reservation 256m --cpus 1.5 --pids-limit 200 app
- Exceed the memory limit → the kernel OOM-kills the container (
OOMKilled: true, exit 137). --cpusis a CFS quota; exceeding it throttles rather than kills.- Without limits, one container can starve the host.
Init and signals
Use docker run --init (tini) when the app spawns child processes and doesn't reap them, or when it doesn't handle signals itself as PID 1. The kernel gives PID 1 special treatment: signals without a handler installed are ignored for PID 1, so a naive app as PID 1 may ignore SIGTERM entirely.
Logging
The default json-file driver writes container stdout/stderr to /var/lib/docker/containers/<id>/<id>-json.log — unbounded by default, a classic disk-filler. Cap it globally in /etc/docker/daemon.json:
{ "log-driver": "json-file", "log-opts": { "max-size": "50m", "max-file": "3" } }
Other drivers: local, awslogs (CloudWatch), fluentd, journald. Apps should log to stdout/stderr (twelve-factor), not files inside the container. In Kubernetes, containerd writes logs to /var/log/pods and the kubelet rotates them; a DaemonSet (Fluent Bit) ships them.