In this tutorial, we'll explore how to use environment variables in Docker Compose to manage the configuration settings for your services. By the end of this tutorial, you should be able to:
Prerequisites: Basic knowledge of Docker and Docker Compose is required.
Environment variables are a way of passing configuration settings to your applications. Docker Compose uses them to set environment variables inside containers, or to define values that are used in the Compose file.
Docker Compose supports two ways to set environment variables:
You can set environment variables directly in a service’s configuration:
services:
web:
environment:
- VARIABLE_NAME=value
Alternatively, you can use a separate file to specify environment variables:
services:
web:
env_file:
- .env
In the .env
file, you should define your variables like so:
VARIABLE_NAME=value
Sensitive data, such as passwords or API keys, should not be included directly in the Docker Compose file. Instead, use environment variables to pass this data to the containers.
In the following Docker Compose file, we set an environment variable DEBUG
for the web
service:
services:
web:
environment:
- DEBUG=true
In this example, we’ll use an environment file to set the DEBUG
variable:
services:
web:
env_file:
- .env
And in the .env
file:
DEBUG=true
In this tutorial, we've learned how to use environment variables in Docker Compose to manage configuration settings for your services. We've also covered how to securely handle sensitive data with environment variables.
To learn more, you can refer to the official Docker Compose documentation on environment variables.
Create a Docker Compose file that defines an environment variable for a MySQL service setting the root password. Hint: The environment variable is MYSQL_ROOT_PASSWORD.
Create a Docker Compose file that uses an environment file to set the root password for a MySQL service.
services:
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: mysecretpassword
services:
db:
image: mysql:5.7
env_file:
- .env
And in the .env
file:
MYSQL_ROOT_PASSWORD=mysecretpassword
Remember, never commit sensitive data, such as your database password, to your version control system. Always use environment variables for this kind of data.