Docker Compose by Example: Environment Configuration
Configuring runtime variables with this code example showing environment block with map syntax, array syntax alternative, variable substitution from host shell, and loading variables from external env files.
Code
services:
app:
image: my-app
# 1. Map syntax (Dictionary)
environment:
NODE_ENV: production
API_KEY: "secret-123"
# 2. Array syntax (List)
# environment:
# - NODE_ENV=production
# - API_KEY=secret-123
# 3. Pass from host shell
# Value comes from shell running 'docker-compose up'
# environment:
# - HOST_USER=${USER}
# 4. Load from .env file
env_file:
- .env
- .env.productionExplanation
Environment variables configure 12-factor applications at runtime, with Docker Compose supporting definition via the environment key using either map (dictionary) or array (list) syntax. Map syntax provides better readability for simple key-value pairs, while array syntax mirrors traditional environment variable assignment with equals signs.
For sensitive data or large configurations, external files are preferable. The env_file directive instructs Compose to read variables from files like .env and inject them into containers. This keeps Compose files clean and enables excluding secrets from version control by adding .env files to .gitignore. Multiple env files can be specified, with later files overriding earlier ones for environment-specific configurations.
Compose supports variable substitution using ${VARIABLE} syntax to reference values from the shell environment where docker-compose up executes. This enables dynamic configurations like setting image tags or user IDs based on deployment context. Environment variables defined in the Compose file override values from Dockerfiles, providing deployment-specific customization without image rebuilds.
Code Breakdown
environment: defines variables explicitly, overrides Dockerfile values.${USER} pulls value from host's environment variables for dynamic config.env_file: loads variables from files, later files override earlier ones.
