7.2: Interpolation: Use ${DB_PASSWORD} in YAML

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_PASSWORD will be supersecret
  • MYSQL_DATABASE will be monprojet
  • MYSQL_USER will be root

.envDocker Compose will interpolate all variables present in the file.

Best practices for interpolation

  1. 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.

  1. Avoid spaces around= in the .env.
  2. Keep names consistent between.env anddocker-compose.yml to 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.