docker-compose.yml.envNow that we have our file, it’s time to link it to our file. This is called variable interpolation.
How does it work?
Docker Compose will read your.env and automatically replace all references${VARIABLE}with their values.
Example:
# fichier .env
DB_USER=root
DB_PASSWORD=supersecret
DB_NAME=monprojet
In yourdocker-compose.yml:
services:
db:
image: mariadb:10.11
environment:
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
MYSQL_DATABASE: ${DB_NAME}
MYSQL_USER: ${DB_USER}
Result at runtime:
MYSQL_ROOT_PASSWORDwill besupersecretMYSQL_DATABASEwill bemonprojetMYSQL_USERwill beroot
.envDocker Compose will interpolate all variables present in the file.
Best practices for interpolation
- Always provide a default value if necessary:
MYSQL_USER: ${DB_USER:-defaultuser}Here, ifDB_USER does not exist in the .env,Docker will use defaultuser.
- Avoid spaces around
=in the.env. - Keep names consistent between
.envanddocker-compose.ymlto avoid confusion.
Helpful tip
You can check which variables are being used with:
docker compose config
This command displays the final interpolated file, which is very useful for debugging your variables.
📌 Key takeaway:
Interpolation${VAR}allows you to decouple configuration from code. You can change your passwords, ports, or database names without touching the YAML, making your stack flexible and portable.