Docker Compose YAML Environment Variables to .env

Extract and convert environment variables defined in docker-compose.yml to standalone .env files. Covers both list and mapping formats used by Docker Compose.

Real-World Configs

Detailed Explanation

Docker Compose supports two formats for defining environment variables in services, and both can be extracted to a standalone .env file. Understanding this conversion is essential for managing configuration across Docker environments.

Docker Compose with environment variables (list format):

services:
  api:
    image: myapp:latest
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgres://user:pass@db:5432/myapp
      - REDIS_URL=redis://redis:6379
      - JWT_SECRET=super-secret-key
      - LOG_LEVEL=info
      - CORS_ORIGINS=https://app.example.com,https://admin.example.com

Docker Compose with environment variables (mapping format):

services:
  api:
    image: myapp:latest
    environment:
      NODE_ENV: production
      DATABASE_URL: "postgres://user:pass@db:5432/myapp"
      REDIS_URL: "redis://redis:6379"
      JWT_SECRET: super-secret-key
      LOG_LEVEL: info
      CORS_ORIGINS: "https://app.example.com,https://admin.example.com"

Extracted .env file:

NODE_ENV=production
DATABASE_URL=postgres://user:pass@db:5432/myapp
REDIS_URL=redis://redis:6379
JWT_SECRET=super-secret-key
LOG_LEVEL=info
CORS_ORIGINS=https://app.example.com,https://admin.example.com

Then reference it in docker-compose.yml:

services:
  api:
    image: myapp:latest
    env_file:
      - .env

Important conversion details:

  1. List format (- KEY=VALUE) is directly convertible -- each entry is already in ENV syntax. Just remove the - prefix.
  2. Mapping format (KEY: VALUE) requires converting YAML's colon-space separator to the equals sign. Values may need quoting if they contain special characters.
  3. Mixed sources. Docker Compose can combine environment:, env_file:, and shell environment variables. Values in environment: override those from env_file:.

Multi-service extraction: When a docker-compose.yml has multiple services, you may want separate .env files:

# api.env
NODE_ENV=production
JWT_SECRET=super-secret-key

# db.env
POSTGRES_DB=myapp
POSTGRES_PASSWORD=dbpassword

YAML-specific gotchas in Docker Compose:

  • Unquoted yes/no values are parsed as booleans by YAML, not as strings. Always quote: FEATURE_FLAG: "yes".
  • Port-like values (e.g., 3000:3000) must be quoted as strings.
  • Values with $ need escaping ($$) or will be interpreted as variable substitution.

Use Case

Extracting environment variables from a complex multi-service docker-compose.yml file into a centralized .env file for easier secrets management and to avoid committing sensitive values to version control.

Try It — YAML ↔ ENV Converter

Open full tool