🔧 Configure Containers with Environment Variables
Hardcoded config in image is bad. Environment variables configure containers at runtime. Change without rebuild.
📝 Setting Environment Variables
# Docker run
docker run -e DB_HOST=postgres -e DB_USER=admin myapp
# Dockerfile
ENV DB_HOST=postgres
ENV DB_USER=admin
# Using .env file
docker run --env-file .env myapp
# Docker Compose
services:
app:
image: myapp
environment:
- DB_HOST=postgres
- DB_USER=admin
env_file:
- .env
# Kubernetes
apiVersion: v1
kind: Pod
spec:
containers:
- name: app
env:
- name: DB_HOST
value: postgres
🎯 .env File Example
# .env
DB_HOST=postgres
DB_PORT=5432
DB_USER=admin
DB_PASSWORD=secret
REDIS_HOST=redis
REDIS_PORT=6379
APP_ENV=production
LOG_LEVEL=info
# docker-compose.yml
services:
app:
image: myapp
env_file:
- .env
# Inside container
# Environment variables are available as process.env
💡 Best Practices
- Never commit .env to Git
- Use .env.example for template
- Secrets: Use Docker secrets or Kubernetes secrets
- Override per environment (dev, staging, prod)
- Validate required environment variables
“Environment variables decouple config from code. Change DB connection without rebuild. Essential for DevOps.”
