Environment Variables and Configuration
What you'll learn: How to inject dynamic configuration into your Docker containers using environment variables in Compose files.
The Core Concept
Environment variables are like labeled boxes of information your container can read at runtime—database URLs, API keys, feature flags, or any setting that might change between environments (dev, staging, production). Docker Compose gives you three primary ways to pass these variables to your services:
environmentkey - Define variables directly in yourdocker-compose.yml:
services:
web:
image: myapp
environment:
DATABASE_URL: postgres://db:5432/mydb
DEBUG_MODE: "true"
env_filekey - Load variables from external files, keeping secrets out of version control:
services:
web:
image: myapp
env_file:
- .env
- .env.production
- Variable substitution - Reference your host machine's environment or
.envfile in the Compose file itself:
services:
web:
image: myapp
environment:
API_KEY: ${API_KEY}
PORT: ${PORT:-8080} # default value if not set
Why This Matters
Think of environment variables as the "settings panel" for your containerized app. Instead of rebuilding images for each environment, you configure behavior externally. The app code stays identical; only the runtime configuration changes.
Key Takeaway: Docker Compose lets you configure containers flexibly using environment for inline values, env_file for external configuration files, and ${VAR} substitution for dynamic values from your shell or .env file—enabling the same image to run differently across environments.