Environment Variables in Docker: A Complete Guide
Docker offers multiple ways to manage environment variables. Understanding each method and when to use it is crucial for secure, maintainable containerized applications.
Methods for Setting Environment Variables
Docker provides several ways to pass environment variables to containers, each with different use cases and security implications.
1. Command Line with -e Flag
The simplest method is passing variables directly when running a container:
Pros: Simple, no files needed
Cons: Variables visible in process lists, hard to manage many variables
2. Environment Files (--env-file)
Load variables from a file instead of the command line:
Pros: Easy to manage, can use different files for different environments
Cons: File must exist on host, still plaintext
3. Dockerfile ENV Instruction
Set default environment variables in the image itself:
Important:Never put secrets in ENV instructions! They're baked into the image and visible to anyone with image access.
4. Docker Compose
Docker Compose offers the most flexible environment configuration:
Variable Interpolation
Compose automatically loads a .env file in the same directory and allows variable substitution:
5. Docker Secrets (Swarm/Kubernetes)
For production environments, Docker Secrets provide encrypted storage:
Secrets are mounted as files at /run/secrets/secret_name. Your application reads the file contents rather than an environment variable:
Multi-Stage Builds and Secrets
Be careful with secrets during build time. Use Docker BuildKit's secret mounting:
Production Best Practices
1. Never Bake Secrets into Images
Environment variables set with ENV or ARG in Dockerfiles are visible in the image layers. Always inject secrets at runtime:
2. Use Read-Only Secrets
When using secret files, mount them read-only to prevent accidental modification:
3. Different Configs for Different Environments
Use compose file overrides for environment-specific configuration:
4. Validate Environment at Startup
Have your application validate required environment variables on startup:
5. Use .dockerignore
Prevent .env files from being copied into images:
Key Takeaways
- Use
--env-filefor simple deployments - Use Docker Compose for complex multi-container setups
- Use Docker Secrets for production-grade secret management
- Never bake secrets into Docker images
- Use BuildKit secret mounts for build-time secrets
- Validate required environment variables at container startup