12. Configuration Management with Environment Variables
The 12-Factor App and Docker Configuration
The 12-Factor App methodology states that configuration should be stored in the environment, not baked into the image. Docker provides several ways to inject configuration at runtime, keeping your images environment-agnostic.
Environment Variable Precedence
Environment variables can be set in multiple places, with later sources overriding earlier ones. The precedence (highest to lowest) is: command line `-e` flags, shell environment variables when running `docker run`, `.env` file variables, Compose `environment` section, and finally the `ENV` instruction in the Dockerfile. For production, use the command line or Compose with a `.env` file to inject secrets. Never bake production secrets into the Dockerfile — they will be visible in `docker history`.
# Highest precedence: command line -e docker run -e DATABASE_URL=postgres://prod:pass@db/prod myapp # From shell environment export DATABASE_URL=postgres://prod:pass@db/prod docker run myapp # Inherits from shell # From .env file (with Compose) docker compose up # Reads .env automatically # From Compose environment section (in YAML) environment: - DATABASE_URL=postgres://prod:pass@db/prod # Lowest precedence: Dockerfile ENV ENV DATABASE_URL=postgres://dev:pass@db/dev
Docker Secrets (Swarm Mode)
Environment variables are not secure — they are visible in `docker inspect`, `docker exec env`, and can be leaked in logs. For production secrets (passwords, API keys, TLS certificates), use Docker Secrets (Swarm mode) or external secret management (HashiCorp Vault, AWS Secrets Manager). Docker Secrets are encrypted during transit and at rest, and are mounted as files in `/run/secrets/`, not as environment variables. This prevents accidental exposure in logs or debug commands.
# Create a secret from stdin echo "supersecretpassword" | docker secret create db_password - # Create secret from file docker secret create db_password ./db_password.txt # Use secret in a service docker service create --secret db_password --name db postgres # Inside the container, secret is at /run/secrets/db_password # Application reads: cat /run/secrets/db_password # In Compose for Swarm (docker-stack.yml) services: db: secrets: - db_password secrets: db_password: external: true
Knowledge Check
Ready to test your understanding of 12. Configuration Management with Environment Variables?