'WARNING: The DB_USER variable is not set

I am using docker compose for my project. And I have a strange error after docker-compose up --build:

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

How can I fix this error? (I was trying both ./.env and .env) What is wrong?

Project structure

.
├── docker-compose.yml
├── project
   |---Dockerfile
|__.env

.env

DB_USER=postgres
DB_PASSWORD=post222
DB_NAME=edo_db
DB_PORT=5444

DATABASE_URL=postgres://postgres:post222@db:5432/edo_db"
DEBUG=1

docker-compose.yml

version: '3.9'

services:
  django:
    build: ./project # path to Dockerfile
    command: sh -c "
      python manage.py makemigrations
      && python manage.py migrate  
      && gunicorn --bind 0.0.0.0:8000 core_app.wsgi"
    volumes:
      - ./project:/project
      - ./project/static:/project/static
    expose:
      - 8000
    env_file:
      - ./.env
  
  db:
    image: postgres:13-alpine
    volumes:
      - pg_data:/var/lib/postgresql/data/
    expose: 
      - 5432
    env_file:
      - ./.env
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=${DB_NAME}
  
  nginx:
    image: nginx:1.19.8-alpine
    depends_on: 
      - django
    env_file:
      - ./.env
    ports: 
      - "80:80"
    volumes:
      - ./project/static:/var/www/html/static
      - ./project/nginx-conf.d/:/etc/nginx/conf.d
  
volumes:
    pg_data:
    static:


Solution 1:[1]

The reason of the error was typo in .env file: Replased

DATABASE_URL=postgres://postgres:post222@db:5432/edo_db"

with

DATABASE_URL=postgres://postgres:post222@db:5432/edo_db

Solution 2:[2]

echo $DB_USER  #  see whether this variable is defined or not prior to below

to engage the variables in file .env you must source the .env file

source .env    # good

source ./.env  # also good ... same as above yet safer

. .env  #  also good since . is same command source

. ./.env  #  good too also sources file .env

.env  #  BAD - this just executes the file which happens in a subshell and has NO impact up on parent shell ( in the terminal you executed it from ) 

now after you have source the file confirm the variable is now defined

echo $DB_USER

now do your docker-compose up

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex
Solution 2