Env Vars & Restart Policies
Configuration Without Rebuilding
An environment variable is a small named piece of text that the operating system hands to a running program - things like PATH or HOME that you may have seen in a regular Linux shell. Docker containers use them for exactly the same purpose: as a way to hand a program information without editing any files inside it.
This matters because of a rule of thumb called twelve-factor: the same image should run in dev, staging and production unchanged, with only the config differing. Environment variables are how that config gets injected at run time instead of being baked into the image:
$ 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).