Managing environment variables effectively is crucial for configuring and deploying containerized applications using Docker Compose. This blog post provides a comprehensive guide to understanding and utilizing environment variables within your Compose setups.
You can define environment variables in several ways:
.env
file in the same directory as your docker-compose.yml
file. Variables defined here are loaded by default.# .env file
POSTGRES_USER=example
POSTGRES_PASSWORD=password
docker-compose.yml
file under the environment
key for a specific service.version: '3.8'
services:
web:
image: nginx:latest
environment:
VIRTUAL_HOST: example.com
VIRTUAL_PORT: 80
docker-compose
commands.DATABASE_URL=postgres://user:password@host:port/database docker-compose up -d
env_file
key. These files follow the same format as .env
files.version: '3.8'
services:
db:
image: postgres:latest
env_file:
- db.env
Leverage variable substitution to define dynamic values based on other environment variables.
version: '3.8'
services:
web:
image: my-web-app:${VERSION}
environment:
VERSION: 1.0 # Or pass VERSION at runtime
Understand the order of precedence to avoid unexpected behavior:
docker-compose.yml
(or .env
if not explicitly overridden)env_file
.env
file in the project directory (loaded by default if not superseded)Avoid storing sensitive information directly in your Compose file or .env
files. Use Docker secrets for managing sensitive data securely.
version: '3.8'
services:
db:
image: postgres:latest
secrets:
- db_password
secrets:
db_password:
file: db_password.txt
Use docker-compose config
to view the resolved environment variables for your services. This helps in debugging and verifying the correct values are being used.
.env
files out of version control for security reasons.By following these practices, you can effectively utilize environment variables within Docker Compose to streamline your development and deployment workflows.