In a Docker Compose, you can set environment variables in a service’s containers or overwrite variables that are defined in the Dockerfile
of the images you’re running.
To pass the environment variables to the containers, you can use the environment
key in a docker-compose.yml
file, that works just like a docker run -e VAR=VALUE ...
command.
Alternatively, you can pass multiple environment variables from an external file with the env_file
option, just like with a docker run --env-file=FILE ...
command.
In this short note i will show the examples of how to set the environment variables in the Docker Compose using the environment
and env_file
options.
Cool Tip: How to specify a path to the Dockerfile
in a Docker Compose! Read more →
Set Environment Variables in Docker Compose
To set the environment variables in the docker-compose.yml
file, use the environment
option as in the example below:
version: '3' services: db: image: mysql:latest environment: - MYSQL_DATABASE: 'db' - MYSQL_USER: 'user' - MYSQL_PASSWORD: 'password' - MYSQL_ROOT_PASSWORD: 'password'
To pass multiple environment variables from an external file, create the .env
file with the contents as follows:
# .env MYSQL_DATABASE: 'db' MYSQL_USER: 'user' MYSQL_PASSWORD: 'password' MYSQL_ROOT_PASSWORD: 'password'
… and use the env_file
option in the docker-compose.yml
file to pass these variables:
version: '3' services: db: image: mysql:latest env_file: .env
You can also set environment variables from multiple files as follows:
version: '3' services: db: image: mysql:latest env_file: - ./common.env - ./apps/db.env
Environment Files Order: The environment files in the Docker Compose are processed from the top down. For example, for the same variable specified in the file ./common.env
and assigned a different value in the file ./apps/db.env
, the value from ./apps/db.env
stands as this file is listed below (after) the ./common.env
file.