Environment Files Done Right: Patterns for .env Management
Secure patterns for managing environment variables across development, staging, and production
February 26, 2026 · 6 min · 1073 words · Rob Washington
Table of Contents
Environment files are deceptively simple. A few KEY=value pairs, what could go wrong? Quite a bit, actually. Here’s how to manage them without shooting yourself in the foot.
# No quotes needed for simple valuesSIMPLE=hello
# Single quotes: literal (no expansion)SINGLE='$PATH stays literal'# Double quotes: allows spaces, some expansionDOUBLE="hello world"# Multiline valuesMULTILINE="line one
line two
line three"# Or use \n (parser-dependent)MULTILINE_ALT="line one\nline two\nline three"
When in doubt, use double quotes for values with spaces or special characters.
# Don't bake secrets into imagesENVAPI_KEY=secret # ❌ Bad - visible in image layers# Pass at runtime instead# docker run -e API_KEY=secret myapp # ✅ Good
For Docker Compose:
1
2
3
4
5
6
7
8
9
10
11
12
services:app:environment:# Direct value (avoid for secrets)DEBUG:"true"# From host environmentAPI_KEY:${API_KEY}# From .env file (preferred)env_file:- .env
#!/bin/bash
# setup.shif[ ! -f .env ];then cp .env.example .env
echo"Created .env from .env.example"echo"Please edit .env with your local values"exit1fi# Validate required varssource .env
REQUIRED="DATABASE_URL API_KEY"for var in $REQUIRED;doif[ -z "${!var}"];thenecho"Missing required variable: $var"exit1fidoneecho"Environment validated ✓"
Environment files are a solved problem—if you follow the patterns. Keep secrets out of git, validate early, layer your configurations, and use proper secret management for production. Your future self (and your security team) will thank you.
📬 Get the Newsletter
Weekly insights on DevOps, automation, and CLI mastery. No spam, unsubscribe anytime.