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 a Dockerfile in 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.
Hi! This is a good piece; short and to the point, thanks!
May I add that with the “environment” option for specifying environment variables individually, docker-compose throws an error requiring that a string be passed. This is because you’ve prefixed the variable definition with the “-” or hyphen. If you want to use a colon, you should drop the hyphen. You may use the hyphen if you exchange the colon for an equal sign instead “=”. See the link below.
https://stackoverflow.com/questions/66853440/docker-compose-error-invalid-type-it-should-be-a-string