Docker Compose to .env & .env.example Extractor

Parse docker-compose.yml files to extract, deduplicate, and generate clean .env and .env.example templates with 1-click secret sanitization.

How to Extract .env from Docker Compose

1

Paste docker-compose.yml

Paste your Compose file containing service environment: lists, maps, or ${VAR} interpolations.

2

Select Extraction Mode

Choose flat output, service grouped, or check Generate .env.example to mask secrets.

3

Save .env File

Copy or download the output and save it as .env in your project root next to docker-compose.yml.

Tool Options

List & Map Syntax Support

Seamlessly extracts both YAML array items (- KEY=val) and object key-values (KEY: val).

Automatic Secret Masking

Detects password, secret, token, and key variables and automatically substitutes placeholder tokens for .env.example.

Client-Side Security

100% in-browser processing guarantees your private infrastructure configuration and API tokens are never uploaded.

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the Docker Compose to .env & .env.example Extractor do?

The Docker Compose to .env Extractor parses docker-compose.yml files to discover, extract, and consolidate all environment variables into clean .env files or .env.example templates. It supports both YAML list syntax (- KEY=val) and dictionary map syntax (KEY: val), extracts interpolated shell parameters (${VAR} and ${VAR:-default}), masks sensitive credentials, and generates sanitized Compose files referencing external environment variables.

Core Concepts

Understanding Docker Compose environment mechanics helps organize configuration layers:

  • environment block syntax: Compose allows defining environment variables either as an array of KEY=value strings or as a mapping dictionary of KEY: value pairs.
  • Variable Interpolation (${VAR:-default}): Values defined inside Compose strings (e.g. image: "app:${TAG:-latest}") are evaluated from the host shell or a local .env file at runtime.
  • Twelve-Factor Separation: Storing credentials and environment-specific settings in .env files keeps your docker-compose.yml clean, portable, and safe for version control.

How to use the tool?

  1. Paste docker-compose.yml: Paste your full Compose file or service definitions into the input editor.
  2. Configure Extraction Options:
    • Generate .env.example: Automatically replaces passwords, API tokens, database connection strings, and secret keys with placeholder strings (e.g. your_api_secret_here).
    • Group by Service: Inserts commented header blocks (# Service: web) separating variables by their parent service.
    • Sanitize Compose YAML: Generates a modified docker-compose.yml where hardcoded values inside environment: are replaced with clean ${VARIABLE_NAME} references.
  3. Copy or Download Output: Save the generated output as .env or .env.example directly in your project root next to your docker-compose.yml.

Related Developer Utilities

If you work with Docker containers, cloud deployments, and YAML configurations, explore these complementary tools:

REST API Integration

Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/docker/docker-compose-to-env) to programmatically parse docker-compose.yml files and extract, deduplicate, and sanitize environment variables into .env or .env.example templates.

API Request Parameters

Name Type Description Example
rawText String The raw docker-compose.yml file content to parse. "services:\n app:\n environment:\n - PORT=8080"
generateExample Boolean Whether to mask sensitive values for .env.example. false
groupByService Boolean Whether to group extracted variables by service comments. false
sanitizeCompose Boolean Whether to return sanitized Compose YAML with ${VAR} references. false

API Request Payload Examples

cURL

curl -X POST https://blueutils.com/api/docker/docker-compose-to-env \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "services:\n  web:\n    environment:\n      - DATABASE_URL=postgres://user:pass@db:5432/db\n      - PORT=8080",
    "generateExample": true
  }'

Python

import requests

url = "https://blueutils.com/api/docker/docker-compose-to-env"
payload = {
    "rawText": "services:\n  web:\n    environment:\n      - DATABASE_URL=postgres://user:pass@db:5432/db\n      - PORT=8080",
    "generateExample": True
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = """
            {
                "rawText": "services:\\n  web:\\n    environment:\\n      - DATABASE_URL=postgres://user:pass@db:5432/db\\n      - PORT=8080",
                "generateExample": true
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/docker/docker-compose-to-env"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Indicates whether extraction succeeded. true
totalVariables Number Total count of unique environment variables extracted. 2
serviceCount Number Count of services containing environment variables. 1
converted String Formatted .env or .env.example file text. "DATABASE_URL=...\nPORT=8080"
sanitizedCompose String Sanitized Compose YAML with variable interpolations. "services:\n web:\n ..."

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "totalVariables": 2,
  "serviceCount": 1,
  "variables": {
    "DATABASE_URL": "postgres://user:pass@db:5432/db",
    "PORT": "8080"
  },
  "converted": "# Generated from docker-compose.yml via Blueutils\n# Environment Variable Template (.env.example)\n\nDATABASE_URL=localhost\nPORT=8080",
  "sanitizedCompose": null
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "Invalid YAML syntax: unexpected end of stream"
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to extract .env from Docker Compose?

Integrating the Docker Compose Environment Extractor API into repository linters, pre-commit hooks, or setup scripts provides practical advantages:

  • Rapid Script Validation: Enables developers and infrastructure teams to automatically verify and generate .env.example templates whenever docker-compose.yml changes in Git pull requests.
  • Optimized Token Efficiency for AI Agents: Offloading YAML parsing, variable discovery, and placeholder generation to an API saves hundreds of prompt tokens during autonomous workspace setup.
  • Deterministic Accuracy Without Hallucinations: Standardizes extraction across diverse Compose syntax styles (arrays, objects, ${VAR} defaults) without YAML syntax errors or missed keys.

Native Usage

How to extract and inspect Docker Compose environment variables locally:

Windows (CMD / PowerShell)

# Using Python standard library and PyYAML to inspect environment keys
python -c "import yaml; doc=yaml.safe_load(open('docker-compose.yml')); [print(f'{k}={v}') for s in doc.get('services',{}).values() for k,v in (s.get('environment') or {}).items()]"

Linux / Unix (Bash)

# Docker Compose native command to verify active interpolated variables
docker compose config --environment

# Or extract environment keys directly using Python CLI
python3 -c "import yaml; doc=yaml.safe_load(open('docker-compose.yml')); [print(f'{k}={v}') for s in doc.get('services',{}).values() for k,v in (s.get('environment') or {}).items() if isinstance(s.get('environment'), dict)]"

Python

Using PyYAML in Python scripts to extract and write .env files:

import yaml

with open("docker-compose.yml") as f:
    doc = yaml.safe_load(f) or {}

services = doc.get("services", {})
env_vars = {}

for s_name, s_cfg in services.items():
    env = s_cfg.get("environment", {})
    if isinstance(env, list):
        for item in env:
            if "=" in item:
                k, v = item.split("=", 1)
                env_vars[k.strip()] = v.strip()
    elif isinstance(env, dict):
        for k, v in env.items():
            env_vars[k] = str(v) if v is not None else ""

with open(".env", "w") as out:
    for k, v in sorted(env_vars.items()):
        out.write(f"{k}={v}\n")
print(f"Extracted {len(env_vars)} variables into .env")

Java

Using standard Java ProcessBuilder to run docker compose config:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class DockerEnvExtractor {
    public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder("docker", "compose", "config", "--environment");
        pb.redirectErrorStream(true);

        try {
            Process process = pb.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }
            int exitCode = process.waitFor();
            System.out.println("Exit code: " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Frequently Asked Questions (FAQ)

How do I extract environment variables from docker-compose.yml?

Paste your docker-compose.yml file into the input box and click Extract & Generate .env. The tool extracts all variables defined in list syntax (- KEY=val), map syntax (KEY: val), and interpolated placeholders (${VAR}).

How does .env.example generation work?

When Generate .env.example is enabled, the tool automatically detects passwords, secrets, tokens, and keys, and replaces them with placeholder tokens (e.g. your_api_key_here).

Are my Docker secrets stored or transmitted?

No. All extraction and sanitization logic runs 100% client-side inside your browser memory. Your Docker Compose files and tokens are never uploaded or saved remotely.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.