Environment & Config
The same image should run in development, staging and production. What differs between them (database URLs, log levels, feature flags, credentials) is configuration, and the container-friendly way to supply it is through environment variables and mounted config files, not by baking it into the image. This is the "config" rule of the twelve-factor app methodology.
Setting environment variables
docker run -e LOG_LEVEL=debug -e PORT=9000 shop:1.4
docker run -e LOG_LEVEL shop:1.4 # copy LOG_LEVEL's value from your shell
docker run --env-file ./prod.env shop:1.4 # read KEY=value lines from a file
docker exec shop env # see the variables in a running containerA prod.env file:
# comments and blank lines are ignored
DATABASE_URL=postgres://shop@db:5432/shop
LOG_LEVEL=info
GREETING="Hello"Warning:
docker run --env-filetakes everything after the first=literally:GREETINGabove is"Hello"with the quote characters. Compose'senv_fileand.envhandling do strip quotes. Leave quotes out of files you pass todocker run.
Which value wins?
Values can come from the image (ENV in the Dockerfile), from env files and from -e flags. Later sources override earlier ones:
image ENV < --env-file (in order given) < -e flagsThe model applies those rules, including the literal-quote behaviour and -e NAME without a value (taken from the caller's shell, or skipped if it is not set there):
image_env = {"PORT": "8000", "LOG_LEVEL": "warning", "PYTHONUNBUFFERED": "1"}
shell = {"LOG_LEVEL": "debug", "HOME": "/home/ada"}
def read_env_file(text):
values = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
key, sep, value = line.partition("=")
if sep:
values[key] = value # taken literally, quotes included
elif key in shell:
values[key] = shell[key]
return values
def resolve(env_files, flags):
env = dict(image_env)
for text in env_files:
env.update(read_env_file(text))
for flag in flags:
key, sep, value = flag.partition("=")
if sep:
env[key] = value
elif key in shell:
env[key] = shell[key]
return env
prod_env = 'DATABASE_URL=postgres://shop@db:5432/shop\nLOG_LEVEL=info\nGREETING="Hello"\n'
final = resolve([prod_env], ["PORT=9000", "LOG_LEVEL", "MISSING_VAR"])
for key in sorted(final):
print(f"{key}={final[key]}")DATABASE_URL=postgres://shop@db:5432/shop
GREETING="Hello"
LOG_LEVEL=debug
PORT=9000
PYTHONUNBUFFERED=1
LOG_LEVEL went warning (image) → info (env file) → debug (from the shell via -e LOG_LEVEL). MISSING_VAR was not set in the shell, so it was left out.
Reading configuration in the app
Environment variables are always strings. Convert and validate them once at start-up, and fail fast with a clear message rather than crashing later on the first request:
def load_config(env):
errors = []
def require(name):
value = env.get(name)
if not value:
errors.append(f"{name} is required")
return value
def integer(name, default):
raw = env.get(name, str(default))
if not raw.isdigit():
errors.append(f"{name} must be a whole number, got {raw!r}")
return default
return int(raw)
config = {
"database_url": require("DATABASE_URL"),
"port": integer("PORT", 8000),
"workers": integer("WORKERS", 2),
"debug": env.get("DEBUG", "false").lower() in ("1", "true", "yes"),
}
if errors:
raise SystemExit("config error: " + "; ".join(errors))
return config
print(load_config({"DATABASE_URL": "postgres://db/shop", "PORT": "9000", "DEBUG": "True"}))
try:
load_config({"PORT": "80a"})
except SystemExit as e:
print(e){'database_url': 'postgres://db/shop', 'port': 9000, 'workers': 2, 'debug': True}
config error: DATABASE_URL is required; PORT must be a whole number, got '80a'
Config files
For larger configuration (an nginx.conf, a YAML file) mount a file instead of using dozens of variables:
docker run -d -v "$PWD/nginx.conf:/etc/nginx/nginx.conf:ro" -p 8080:80 nginx:1.27The :ro makes the mount read-only inside the container. The next lesson covers mounts in detail.
What not to put in environment variables
Environment variables are convenient, but they are visible to anyone who can run docker inspect, they are inherited by every child process, and they often end up in logs and crash reports. For passwords and API keys prefer:
- Compose secrets / Swarm secrets / Kubernetes Secrets, mounted as files under
/run/secrets/; - the
*_FILEconvention many official images support, for examplePOSTGRES_PASSWORD_FILE=/run/secrets/db_password.
docker inspect --format '{{json .Config.Env}}' shopSample output:
["PORT=9000","LOG_LEVEL=debug","DATABASE_URL=postgres://shop:s3cret@db/shop","PYTHONUNBUFFERED=1"]There is the password, in plain text. The Security lesson returns to this.
Test yourself
The image has ENV PORT=8000, the env file says PORT=8500, and you pass -e PORT=9000. Which value does the app see?
- 8000
- 8500
- 9000
- All three
An env file passed with docker run --env-file contains NAME="Ada". What is the value of NAME?
- Ada
- "Ada" (with the quote characters)
- Empty
- It causes an error
Why should an app validate its environment variables at start-up?
- Environment variables are always numbers
- They are strings that may be missing or malformed; failing fast gives a clear error instead of a later crash
- Docker requires it
- It makes the image smaller