Env Vars & Restart Policies
Configuration Without Rebuilding
The twelve-factor rule: same image everywhere, config injected via environment variables:
$ docker run -d --name api \
-e DB_HOST=db.internal \
-e LOG_LEVEL=debug \
orders-api:v1
A missing env var is the single most common cause of a container that "starts then instantly dies" - the app can't find its config and exits. docker logs tells you which one.
Restart Policies
By default a container that dies stays dead, even after the Docker daemon or host reboots. Production containers need a policy:
| Policy | Behavior |
|---|---|
no (default) | never restart |
on-failure | restart only if exit code ≠ 0 |
always | restart forever - even after you docker stop it (on daemon restart) |
unless-stopped | restart after crashes/reboots, but respect a manual stop |
$ docker run -d --restart unless-stopped --name worker myworker:v3
Tip: unless-stopped is the production default of choice: survives reboots, but when an engineer deliberately stops a container it stays stopped.
Goal: Practice both in the labs: Diagnose the Crash Loop (env vars + logs) and Survive the Reboot (restart policies).