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:
environmentblock syntax: Compose allows defining environment variables either as an array ofKEY=valuestrings or as a mapping dictionary ofKEY: valuepairs.- Variable Interpolation (
${VAR:-default}): Values defined inside Compose strings (e.g.image: "app:${TAG:-latest}") are evaluated from the host shell or a local.envfile at runtime. - Twelve-Factor Separation: Storing credentials and environment-specific settings in
.envfiles keeps yourdocker-compose.ymlclean, portable, and safe for version control.
How to use the tool?
- Paste
docker-compose.yml: Paste your full Compose file or service definitions into the input editor. - 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.ymlwhere hardcoded values insideenvironment:are replaced with clean${VARIABLE_NAME}references.
- Generate
- Copy or Download Output: Save the generated output as
.envor.env.exampledirectly in your project root next to yourdocker-compose.yml.
Related Developer Utilities
If you work with Docker containers, cloud deployments, and YAML configurations, explore these complementary tools:
- .gitignore to .dockerignore Converter: Generate slim
.dockerignorefiles from.gitignorerules and tech stack presets. - Kubernetes Manifest Validator: Validate Kubernetes resource manifests against schemas and best practices.
- YAML to Dotenv Converter: Convert generic nested YAML files into flattened
.envkey-value pairs.
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.exampletemplates wheneverdocker-compose.ymlchanges 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();
}
}
}