Course contentsShow
← Cloud and Infrastructure
Lesson 1051 of 2,98920. Docker in DepthFree lesson

Environment Variables and Configuration

Pass environment variables to containers using environment, env_file, and variable substitution in Compose files.

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:

  1. environment key - Define variables directly in your docker-compose.yml:
services:
  web:
    image: myapp
    environment:
      DATABASE_URL: postgres://db:5432/mydb
      DEBUG_MODE: "true"
  1. env_file key - Load variables from external files, keeping secrets out of version control:
services:
  web:
    image: myapp
    env_file:
      - .env
      - .env.production
  1. Variable substitution - Reference your host machine's environment or .env file 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.