0
0
DockerHow-ToBeginner · 3 min read

How to Use Environment Variables in Docker Compose

In docker-compose.yml, use the environment key under a service to set environment variables as key-value pairs. These variables configure the container's runtime environment and can be defined inline or loaded from an external .env file.
📐

Syntax

The environment section in a docker-compose.yml file defines environment variables for a service. You can specify variables as a list or a map of key-value pairs.

  • List format: Each item is KEY=VALUE.
  • Map format: Use KEY: VALUE pairs.

These variables are passed to the container and can be used by the application inside.

yaml
services:
  app:
    image: myapp:latest
    environment:
      - DEBUG=true
      - PORT=8080

# Or using map format
services:
  app:
    image: myapp:latest
    environment:
      DEBUG: "true"
      PORT: "8080"
💻

Example

This example shows a simple docker-compose.yml file that sets environment variables for a web service. The container prints the environment variables when it starts.

yaml
version: '3.8'
services:
  web:
    image: alpine
    command: sh -c "echo DEBUG=$DEBUG && echo PORT=$PORT"
    environment:
      DEBUG: "true"
      PORT: "3000"
Output
DEBUG=true PORT=3000
⚠️

Common Pitfalls

Common mistakes when using environment variables in Docker Compose include:

  • Using incorrect indentation or syntax in docker-compose.yml.
  • Forgetting to quote string values that look like numbers or booleans, which can cause parsing issues.
  • Expecting environment variables defined in the host shell to automatically pass into containers without explicitly defining them.
  • Not using a .env file when you want to separate secrets or configuration from the compose file.
yaml
services:
  app:
    image: myapp
    environment:
      - DEBUG=true
      - PORT=3000

# Wrong: missing quotes for boolean value might cause issues
services:
  app:
    image: myapp
    environment:
      DEBUG: "true"  # Should be quoted
      PORT: "3000"    # Should be quoted
📊

Quick Reference

FeatureDescriptionExample
Inline environment variablesSet variables directly in docker-compose.ymlenvironment: - KEY=value - DEBUG=true
Map formatUse key-value pairs for clarityenvironment: KEY: value DEBUG: "true"
Using .env filePlace variables in a .env file to load automaticallyKEY=value DEBUG=true
Referencing host variablesUse ${VAR} syntax to inject host env varsenvironment: DEBUG: "${DEBUG}"

Key Takeaways

Use the environment key in docker-compose.yml to set container environment variables.
Specify variables as a list of KEY=VALUE or as a map of key: value pairs.
Quote string values to avoid parsing errors, especially for booleans and numbers.
Use a .env file to keep environment variables separate and secure.
Host environment variables can be injected using ${VAR} syntax in the compose file.