When working with Docker Compose, environment variables make your configuration flexible, secure, and reusable.
Instead of hardcoding sensitive values like passwords or ports directly in docker-compose.yml, you can load them dynamically.
1️⃣ Why Use Environment Variables in Docker Compose?
- Security — Avoid storing secrets directly in the YAML file.
- Reusability — Same Compose file can work for multiple environments (dev, staging, prod).
- Flexibility — Easily change configurations without modifying YAML.
2️⃣ Methods to Use Environment Variables
Method 1 — .env File (Default)
Docker Compose automatically loads variables from a file named .env in the same directory as your docker-compose.yml.
Example .env file:
MYSQL_ROOT_PASSWORD=secret123
MYSQL_DATABASE=myappdb
MYSQL_USER=myuser
MYSQL_PASSWORD=mypassword
Example docker-compose.yml:
version: '3.8'
services:
db:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
✅ Just run:
docker-compose up -d
Method 2 — Pass Variables from Shell
You can export variables in your terminal and reference them.
export MYSQL_ROOT_PASSWORD=secret123
docker-compose up -d
In docker-compose.yml:
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
Method 3 — Inline in Command
MYSQL_ROOT_PASSWORD=secret123 docker-compose up -d
Method 4 — External Environment File
You can specify a custom environment file with --env-file.
docker-compose --env-file config.env up -d
Method 5 — env_file in Compose
version: '3.8'
services:
app:
build: .
env_file:
- config.env
3️⃣ Common Pitfalls
| Problem | Cause | Solution |
|---|---|---|
| Variables not loading | .env file in wrong directory | Place .env next to docker-compose.yml or use --env-file |
| Value contains spaces | Not quoted properly | Wrap value in quotes: VAR="My Value" |
| Secrets in Git | .env committed accidentally | Add .env to .gitignore |
📌 Summary
Best Practices:
- Store secrets in
.env(not indocker-compose.yml). - Use
--env-filefor different environments. - Always
.gitignoreyour.envfile.
Environment variables help you keep configuration clean, safe, and portable across different environments without modifying your Compose file.