Using environment variables in Docker Compose is a common practice to ensure flexible configuration of containerized applications across different environments. Here are some primary methods for introducing and using environment variables in the docker-compose file:
1. .env File
The simplest approach is to create a .env file in the same directory as the docker-compose.yml file. Docker Compose automatically reads the variables from the .env file.
Example:
Create the .env file:
shellDB_USER=root DB_PASS=example
Use these variables in the docker-compose.yml file:
yamlversion: '3.8' services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: ${DB_PASS} MYSQL_USER: ${DB_USER} ports: - "3306:3306"
This way, the environment variables MYSQL_ROOT_PASSWORD and MYSQL_USER will utilize the values defined in the .env file.
2. Using the environment Key
You can directly set environment variables within the service definition in the docker-compose.yml file using the environment key.
Example:
yamlversion: '3.8' services: app: image: myapp environment: - DEBUG=1 - NODE_ENV=production
3. Using the env_file Directive
If you have multiple environment variables, you can place them in separate files and reference them in the docker-compose.yml file using the env_file directive.
Example:
Create the app.env file:
shellDEBUG=1 NODE_ENV=production
Reference it in the docker-compose.yml file:
yamlversion: '3.8' services: app: image: myapp env_file: - app.env
4. Command-Line Variables
You can also pass environment variables via the command line when running the docker-compose command.
Example:
bash$ DB_USER=root DB_PASS=example docker-compose up
These variables can also be used in the docker-compose.yml file.
Summary
Using environment variables effectively separates configuration from application code, enhancing portability and security. Choosing the appropriate method based on specific requirements allows for more flexible and manageable configuration.