Handling Environment Variables, Secrets, and Configurations
When working with multi-container applications, it's important to properly manage environment variables, secrets, and configurations to ensure the security and flexibility of your application.
Environment Variables
Docker Compose allows you to define environment variables for your services in the environment
section of the docker-compose.yml
file. For example:
version: '3'
services:
web:
image: my-web-app
environment:
- DB_HOST=db
- DB_PASSWORD=mypassword
db:
image: postgres
environment:
- POSTGRES_DB=myapp
- POSTGRES_PASSWORD=mypassword
In this example, the web
service has access to the DB_HOST
and DB_PASSWORD
environment variables, while the db
service has access to the POSTGRES_DB
and POSTGRES_PASSWORD
environment variables.
You can also use the env_file
option to load environment variables from a file:
version: '3'
services:
web:
image: my-web-app
env_file:
- web.env
db:
image: postgres
env_file:
- db.env
In this case, the environment variables would be loaded from the web.env
and db.env
files, respectively.
Secrets
Docker Compose also supports the use of secrets, which are sensitive data that should be kept secure. You can define secrets in the secrets
section of the docker-compose.yml
file and then reference them in your service configurations.
version: '3'
services:
web:
image: my-web-app
secrets:
- db-password
db:
image: postgres
secrets:
- db-password
secrets:
db-password:
file: ./db-password.txt
In this example, the db-password
secret is defined and its value is loaded from the db-password.txt
file. The web
and db
services both have access to this secret.
Configurations
In addition to environment variables and secrets, you can also manage other configurations for your services using Docker Compose. For example, you can define volumes to mount configuration files, or use environment variables to parameterize your configurations.
version: '3'
services:
web:
image: my-web-app
volumes:
- ./web-config.yml:/app/config.yml
db:
image: postgres
environment:
- POSTGRES_DB=${DB_NAME}
In this example, the web
service mounts a local configuration file web-config.yml
to the /app/config.yml
path in the container. The db
service uses an environment variable DB_NAME
to set the database name.
By properly managing environment variables, secrets, and configurations in your Docker Compose setup, you can ensure the security and flexibility of your multi-container applications.