Environment variables are essential for configuring services in Docker Compose. They allow you to customize the behavior of your applications without hardcoding values into your code. This guide will explain how to pass environment variables to services in Docker Compose using two primary methods: the environment attribute and the env_file attribute.
1. Using the environment Attribute
The environment attribute allows you to define environment variables directly in your docker-compose.yml file. You can specify variables using either a list or a mapping syntax.
Example of Using environment
version: '3.8'
services:
webapp:
image: my-web-app
environment:
- DEBUG=true
- PORT=8080
In this example, the webapp service will have the DEBUG variable set to true and the PORT variable set to 8080.
Using Shell Variables
You can also pass environment variables from your shell by not providing a value:
version: '3.8'
services:
webapp:
image: my-web-app
environment:
- DEBUG
In this case, the value of DEBUG will be taken from the shell environment where Docker Compose is executed.
2. Using the env_file Attribute
The env_file attribute allows you to specify a file containing environment variables. This method is useful for managing multiple variables and keeping your docker-compose.yml file clean.
Example of Using env_file
version: '3.8'
services:
webapp:
image: my-web-app
env_file:
- webapp.env
In this example, the webapp service will load environment variables from the webapp.env file.
Contents of webapp.env
DEBUG=true
PORT=8080
DATABASE_URL=mysql://user:password@db:3306/mydatabase
This file contains the environment variables that will be available to the webapp service.
3. Key Considerations
- Security: Avoid using environment variables for sensitive information like passwords. Instead, consider using Docker secrets.
- Variable Precedence: Environment variables defined in the
docker-compose.ymlfile will override those in theenv_fileif they share the same name. - Multiple
env_fileSupport: You can specify multipleenv_fileentries, and they will be evaluated in order.
4. Conclusion
Passing environment variables to services in Docker Compose is straightforward and can be done using the environment or env_file attributes. By utilizing these methods, you can effectively manage your application's configuration and ensure a flexible deployment process.
