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:
3
Answers
The reason of the error was typo in .env file: Replased
with
to engage the variables in file .env you must source the .env file
now after you have source the file confirm the variable is now defined
now do your
docker-compose up
Just in case anybody lands here. I had a similar problem where my environment variables for Postgres were not being read by the compose file.
My initial project structure was as follows:
and the
docker-compose.yml
file was as follows:What solved this problem for me was making the following changes:
.env.dev
to.env
;.env
file to the project’s root directory so that it’s on the same level as thedocker-compose.yml
file;docker-compose.yml
fileenv_file
attribute to.env
;My new project structure changed to this:
and my
docker-compose.yml
file changed to this:I hope this helps someone who is facing a similar problem.