9.1.1.4 Compose Environment Config
A focused guide to Compose Environment Config, connecting core concepts with practical Docker and container operations.
Compose environment config covers the various ways a Compose file supplies environment variables to its services — inline values, references to host environment variables, and dedicated environment files — providing flexible configuration without needing to hardcode every value directly into the Compose file itself.
Setting Environment Variables Directly
Values can be specified inline, directly within the service definition.
services:
api:
environment:
- LOG_LEVEL=debug
- NODE_ENV=development
Referencing Host Environment Variables
A variable can be passed through from the host's own environment, useful for values that shouldn't be hardcoded directly into the Compose file.
services:
api:
environment:
- API_KEY=${API_KEY}
export API_KEY=secret123
docker compose up -d
This substitutes the host's API_KEY environment variable value into the service's configuration at startup.
Using a Dedicated Environment File
For services needing many environment variables, a separate file can be referenced instead of listing each one individually.
services:
api:
env_file:
- .env.api
DATABASE_URL=postgres://db:5432/app
LOG_LEVEL=debug
CACHE_TTL=3600
Using a .env File for Compose-Level Variable Substitution
A .env file in the same directory as the Compose file is automatically used for variable substitution throughout the Compose file itself, distinct from the env_file key, which supplies variables specifically to a service's own runtime environment.
APP_VERSION=2.3.0
services:
api:
image: myapi:${APP_VERSION}
Why Compose Environment Config Matters
These various mechanisms together provide flexible, layered control over how configuration values reach each service, supporting everything from simple hardcoded defaults to host-environment-driven values, without ever needing to maintain separate Compose files for different configuration scenarios.