How Can I Use Environment Variables in Docker Compose?

When working with Docker Compose, environment variables make your configuration flexible, secure, and reusable.
Instead of hardcoding sensitive values like passwords or ports directly in docker-compose.yml, you can load them dynamically.


1️⃣ Why Use Environment Variables in Docker Compose?

  • Security — Avoid storing secrets directly in the YAML file.
  • Reusability — Same Compose file can work for multiple environments (dev, staging, prod).
  • Flexibility — Easily change configurations without modifying YAML.

2️⃣ Methods to Use Environment Variables

Method 1 — .env File (Default)

Docker Compose automatically loads variables from a file named .env in the same directory as your docker-compose.yml.

Example .env file:

MYSQL_ROOT_PASSWORD=secret123
MYSQL_DATABASE=myappdb
MYSQL_USER=myuser
MYSQL_PASSWORD=mypassword

Example docker-compose.yml:

version: '3.8'
services:
  db:
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}

✅ Just run:

docker-compose up -d

Method 2 — Pass Variables from Shell

You can export variables in your terminal and reference them.

export MYSQL_ROOT_PASSWORD=secret123
docker-compose up -d

In docker-compose.yml:

environment:
  MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}

Method 3 — Inline in Command

MYSQL_ROOT_PASSWORD=secret123 docker-compose up -d

Method 4 — External Environment File

You can specify a custom environment file with --env-file.

docker-compose --env-file config.env up -d

Method 5 — env_file in Compose

version: '3.8'
services:
  app:
    build: .
    env_file:
      - config.env

3️⃣ Common Pitfalls

ProblemCauseSolution
Variables not loading.env file in wrong directoryPlace .env next to docker-compose.yml or use --env-file
Value contains spacesNot quoted properlyWrap value in quotes: VAR="My Value"
Secrets in Git.env committed accidentallyAdd .env to .gitignore

📌 Summary

Best Practices:

  • Store secrets in .env (not in docker-compose.yml).
  • Use --env-file for different environments.
  • Always .gitignore your .env file.

Environment variables help you keep configuration clean, safe, and portable across different environments without modifying your Compose file.

Sharing Is Caring:

Leave a Comment