Pass environment variable to yml file

Hello folks, I’m kinda very frustrated I’m trying to run simple compose yml file and facing a lot of porblems.
here is my file

version: '3.8'

services:
  db:
    image: postgres:15
    container_name: my_cnt
    restart: always
    env_file:
      - .env.${ENVIRONMENT}
    environment:
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}

and I’m trying to run it with commands

ENVIRONMENT=development docker-compose up -d
ENVIRONMENT=development docker compose up -d
I even tried to explicitly said like

env_file:
      - .env.development

and this file in same folder. But I see errors like The "POSTGRES_USER" variable is not set. Defaulting to a blank string.

what do to? how to run this yml with variables I need?

Compose interpolates variables into the YML from the .env files

The env_file property DOES NOT affect where the compose interpolates from - it only sets the entire container’s environment into what’s within the file

Remove your environment property and you’ll see it’s populated with the contents of .env.development

Tiny addition to @deanayalon’s answer: you can use docker compose config to see the rendered compose file content, and check if the extrapolations did what you expect them to do.

1 Like

Although I would go with @deanayalon’s suggestion, my tiny addition is that as an alternative, you can set the env file used for the compose file in the command line:

docker compose --env-file .env.development up -d

It could help when you have variables that are not directly used in the container. You don’t seem to have those kind of variables, but I often do that so I can have a single env file with a single variable to initialize the database and set the DB connection parameters for one or more containers to connect to the database.