Docker-compose environment variable is not set

Question:

Project tree

/backend
  .env.dev
  docker-compose-dev.yml
  /project

I have the following warning:

docker-compose  -f docker-compose-dev.yml up --build # i am in the /backend directory

WARNING: The DB_USER variable is not set. Defaulting to a blank string.
WARNING: The DB_PASSWORD variable is not set. Defaulting to a blank string.
WARNING: The DB_NAME variable is not set. Defaulting to a blank string.

It means that docker compose don’t see my environment file. How can I fix it?

docker-compose-dev.yml

services:
  django:
    build: ./project # path to Dockerfile
    command: sh -c " 
      sleep 3 && gunicorn -w 8 --bind 0.0.0.0:8800 core_app.wsgi"
    volumes:
      - ./project:/project
      - ./project/static:/project/static
      - ./project/media:/project/media
      - ./project/logs:/project/logs
    expose:
      - 8800
    env_file:
      - ./.env.dev
    depends_on:
      - db

  
  db:
    image: postgres:13-alpine
    volumes:
      - pg_data:/var/lib/postgresql/data/
    expose: 
      - 5432
    ports:
      - "5435:5432"
    env_file:
      - ./.env.dev
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=${DB_NAME}
          .......

How can I enable env file?

P.S
Values are set in the file .env.dev

DB_NAME=db_dev
DB_USER=postgres
DB_PASSWORD=passsss132132
ENV_TYPE=DEV

UPDATE
Found out that this way is working

docker-compose -f docker-compose-dev.yml  --env-file=.env.dev up 
Asked By: mascai

||

Answers:

If the complaint is coming from docker (compose) itself, try to:

  1. rename ./.env.dev to simply .env.dev;
  2. if not yet, rename .env.dev to .env (default) and remove the env_file entry from your compose. That will certainly work, then you can go back to investigate the issue with env_file ([1]).

Update

Now facing the same problem myself — in a similar situation trying to separate the variables of my JupyterHub from that destined to the Jupyter Notebooks –, I digged in a bit more to understand better the role of Compose’s .env and env_file:.

As already informed in the question, the use of option --env-file solves the issue. Which is the right answer for defining docker-compose’s (yaml) environment variables in a file named differently from .env (default).

The env_file option in docker-compose.yaml is meant for the container being run: only the container sees those variables.

I recently posted a similar answer to a similar question :

[1] https://docs.docker.com/compose/env-file/

Answered By: Brandt