Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 111 ยท Containers in Depth

Configuring Containers

Configure Docker containers the 12-factor way: -e, --env-file, precedence rules, mounted config files, entrypoint defaults, nginx templates and secrets pitfalls.

One image should run everywhere: on your laptop, in testing and in production. What changes between those places is configuration: a database address, a log level, a port, a feature switch. If you rebuild the image for every environment, you lose the whole point of images. The Docker way is to keep the image identical and inject configuration when the container starts.

This lesson covers the tools for that: environment variables (-e, --env-file), mounted configuration files, defaults and validation in an entrypoint script, and templating with nginx as a real-world example. It also explains the rules for who wins when the same variable is set in several places, and why environment variables are the wrong place for secrets. All outputs are from real runs.

The twelve-factor idea

A popular set of guidelines for modern services, the twelve-factor app, says: store config in the environment. Concretely:

  • The image contains code and defaults that are safe to publish.
  • Everything that differs per deployment (hosts, credentials, switches) comes from outside.
  • Config is not committed to the repository and not baked into the image.

Environment variables are the simplest implementation: every language can read them, there is no file format to parse, and Docker has first-class support for them.

Setting variables with -e

Use -e (or --env) once per variable. Quote values that contain spaces:

CONSOLE
$ docker run --rm -e GREETING=hello -e NAME="Ada Lovelace" alpine:3.22 sh -c 'echo "$GREETING, $NAME"'
hello, Ada Lovelace

The two other forms of -e are easy to miss. A bare name with no = copies the value from your shell:

CONSOLE
$ export FROM_HOST=value-from-host
$ docker run --rm -e FROM_HOST alpine:3.22 sh -c 'echo "[$FROM_HOST]"'
[value-from-host]
$ docker run --rm -e NOT_SET_ON_HOST alpine:3.22 sh -c 'echo "[$NOT_SET_ON_HOST]"; env | grep -c NOT_SET'
[]
0

If the variable does not exist on the host, nothing is set at all (grep -c counted 0): the variable is absent, not empty. That is handy for passing a token from your shell or CI system without writing it in a command or a file you might commit.

Many variables: --env-file

For more than a few variables, use a file with one NAME=value per line:

TEXT
# comment line
APP_ENV=staging
DEBUG=false
QUOTED="with quotes"
SPACED=two words
EMPTY=
CONSOLE
$ docker run --rm --env-file app.env alpine:3.22 sh -c 'env | grep -E "APP_ENV|DEBUG|QUOTED|SPACED|EMPTY" | sort'
APP_ENV=staging
DEBUG=false
EMPTY=
QUOTED="with quotes"
SPACED=two words

The format of --env-file is deliberately simple, and it differs from what you may be used to in shell scripts:

  • Lines starting with # are comments and blank lines are ignored.
  • Quotes are not interpreted. The value of QUOTED is "with quotes" including the quote marks. Write QUOTED=with quotes instead; everything after the first = is the value, spaces included.
  • There is no variable expansion and no export keyword.
  • EMPTY= sets an empty string, while a line with only NAME (no =) copies from the host like a bare -e NAME.
  • Every value is a string. DEBUG=false is the text false, not a boolean: in a shell [ "$DEBUG" = false ] is true, but if [ "$DEBUG" ] is also true because the string is non-empty. Your application must parse it.

Docker Compose has its own .env and env_file: handling, which is a little different (it supports quotes and ${VAR} interpolation). Do not assume a file that works for docker run --env-file behaves identically in Compose; see Environment, Variables and Secrets.

Who wins? Precedence rules

The same variable can come from the image's ENV (ENV and ARG), from --env-file and from -e. The order, from weakest to strongest:

  1. ENV in the Dockerfile (the image default)
  2. --env-file
  3. -e on the command line

Check it with an image that declares defaults:

DOCKERFILE
FROM alpine:3.22
ENV APP_ENV=development PORT=8080
CMD ["sh","-c","echo env=$APP_ENV port=$PORT"]
CONSOLE
$ docker run --rm tcd-envimg
env=development port=8080
$ docker run --rm --env-file app.env tcd-envimg
env=staging port=8080
$ docker run --rm --env-file app.env -e PORT=9000 tcd-envimg
env=staging port=9000
$ docker run --rm --env-file app.env -e APP_ENV=production alpine:3.22 sh -c 'echo $APP_ENV'
production

Image default, then file override, then explicit flag override. Variables you do not mention keep the image's value (port=8080 in the second run). If you pass both a file and -e for the same name, -e wins.

Configuration in files: mounts

Some software reads a config file (nginx, Redis, Postgres, your own YAML). Mount it into the container, usually read-only:

CONSOLE
$ cat app.conf
mode = fast
retries = 3
$ docker run --rm -v "$PWD/app.conf:/etc/app.conf:ro" alpine:3.22 sh -c 'cat /etc/app.conf; echo x >> /etc/app.conf'
mode = fast
retries = 3
sh: can't create /etc/app.conf: Read-only file system

The :ro suffix makes the mount read-only, so the application (or a bug, or an attacker) cannot rewrite its own configuration. A bind mount is ideal for per-host configuration. More about the syntax is in Bind Mounts. In Compose you will use configs: for the same idea (Environment, Variables and Secrets).

Templating: generating files from environment variables

Often the program wants a file, but you want to drive it with variables. Many official images solve this at startup. The nginx image looks for *.template files in /etc/nginx/templates, replaces ${VARIABLES} using envsubst, and writes the results to /etc/nginx/conf.d:

TEXT
server {
    listen ${NGINX_PORT};
    location / {
        return 200 "hello from ${APP_NAME}\n";
        add_header Content-Type text/plain;
    }
}
CONSOLE
$ docker run -d --name tcd-ng -p 127.0.0.1:18931:8081 \
    -e NGINX_PORT=8081 -e APP_NAME=demo-app \
    -v "$PWD/tpl:/etc/nginx/templates:ro" nginx:alpine
$ docker logs tcd-ng 2>&1 | grep envsubst
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
20-envsubst-on-templates.sh: Running envsubst on /etc/nginx/templates/default.conf.template to /etc/nginx/conf.d/default.conf
$ docker exec tcd-ng cat /etc/nginx/conf.d/default.conf
server {
    listen 8081;
    location / {
        return 200 "hello from demo-app\n";
        add_header Content-Type text/plain;
    }
}
$ curl -s http://127.0.0.1:18931/
hello from demo-app

The container generated its real config from the variables at start-up, so the same image and the same template file work in every environment.

Defaults and validation in an entrypoint script

For your own images, a small entrypoint script is the best place to apply defaults, check required settings, and fail early with a clear message. This script uses POSIX shell parameter expansion:

SH
#!/bin/sh
set -eu

# Required: fail fast with a clear message if missing.
: "${DATABASE_URL:?DATABASE_URL must be set}"

# Optional: sensible defaults.
LOG_LEVEL="${LOG_LEVEL:-info}"
PORT="${PORT:-8080}"

echo "starting on port $PORT with log level $LOG_LEVEL"
echo "database host: ${DATABASE_URL#*@}"

exec "$@"
DOCKERFILE
FROM alpine:3.22
COPY --chmod=755 entrypoint.sh /usr/local/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
CMD ["sleep", "1"]
CONSOLE
$ docker run --rm tcd-entry
/usr/local/bin/entrypoint.sh: line 5: DATABASE_URL: DATABASE_URL must be set
$ docker run --rm -e DATABASE_URL=postgres://app:pw@db:5432/shop tcd-entry
starting on port 8080 with log level info
database host: db:5432/shop
$ docker run --rm -e DATABASE_URL=postgres://app:pw@db:5432/shop -e LOG_LEVEL=debug -e PORT=9000 tcd-entry
starting on port 9000 with log level debug
database host: db:5432/shop

The first run exited immediately with status 2 instead of letting the app crash later with a confusing error. Two details matter here. ${NAME:-default} supplies a fallback when a variable is unset or empty; ${NAME:?message} aborts when it is. And the last line, exec "$@", replaces the shell with the real command, so your application becomes PID 1 and receives stop signals correctly (CMD and ENTRYPOINT and Signals, PID 1 and --init). Notice also that the script prints only the host part of the URL, not the password; do not log secrets.

What should (not) go into environment variables

Environment variables are great for:

  • Mode and behavior switches (APP_ENV, LOG_LEVEL, FEATURE_X).
  • Addresses of other services (DATABASE_HOST, REDIS_URL without credentials).
  • Ports and limits.

They are a poor fit for secrets, for three reasons that I verified:

CONSOLE
$ docker run -d --name tcd-envc -e DB_PASSWORD=hunter2 alpine:3.22 sleep 60
$ docker inspect -f '{{json .Config.Env}}' tcd-envc
["DB_PASSWORD=hunter2","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"]
$ docker exec tcd-envc sh -c 'tr "\0" "\n" < /proc/1/environ | grep DB_'
DB_PASSWORD=hunter2

Anyone who can run docker inspect sees the value, any process in the container can read /proc/*/environ, and many programs dump their environment into crash reports and logs. Child processes inherit the variables as well. For real secrets, pass a file (/run/secrets/...) through mounts, Compose secrets, or an orchestrator, and have the application read the file. Many official images support this convention with _FILE variables (for example POSTGRES_PASSWORD_FILE). Details are in Managing Secrets.

Choosing the right mechanism

Need Use
One or two switches -e NAME=value
A set of variables per environment --env-file prod.env (keep real files out of Git)
Take a value from the caller's shell -e NAME (no =)
A program that wants a config file Read-only bind mount, or a Compose configs: entry
A config file that depends on variables Template + envsubst in the entrypoint
Required settings with clear errors Entrypoint script with ${VAR:?msg}
Passwords, tokens, keys Secret files, not environment variables
Defaults safe to publish ENV in the Dockerfile

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You run docker run -e NOT_SET_ON_HOST alpine env and the variable does not exist in your shell. What happens?

    A bare -e NAME copies the host's value only if it exists. Otherwise nothing is set, and a count of the variable in env output is 0.
  2. 2. An env file contains the line TITLE="My App" (with quote marks). What value does the container see for TITLE?

    docker run --env-file does not interpret quotes: everything after the first equals sign is the value. Write TITLE=My App instead.
  3. 3. The Dockerfile has ENV PORT=8080. You run with --env-file app.env (which sets PORT=7000) and -e PORT=9000. What is PORT?

    Precedence from weakest to strongest is the image's ENV, then --env-file, then -e.
  4. 4. Why does the entrypoint script end with exec "$@"?

    exec replaces the shell process. Without it, the shell stays as PID 1 and the application may not receive SIGTERM from docker stop.
  5. 5. Which is the best way to give a container a password?

    Environment variables are visible in docker inspect, in /proc/<pid>/environ and often in logs. Secret files avoid those leaks.

Summary

  • Keep one image for all environments and inject configuration at run time (twelve-factor style).
  • -e NAME=value sets a variable, -e NAME copies it from the host if it exists, and --env-file loads many at once; env files do not process quotes or expansions and every value is a string.
  • Precedence from weakest to strongest: Dockerfile ENV, --env-file, -e.
  • Mount config files read-only (:ro), or generate them from variables with templates such as nginx's envsubst support.
  • Use an entrypoint script for defaults (${VAR:-default}), required settings (${VAR:?message}) and exec "$@".
  • Do not put secrets in environment variables: docker inspect and /proc/*/environ reveal them. Use secret files instead.

Next: Resource Limits