docer-compose.yml in Django project: environment variables are not created from the .env file

355 Views Asked by At

My docker-compose.yml:

version: '3.8'

services:
  web:
    build: ./app
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - ./app/:/usr/src/app/
    ports:
      - 8000:8000
    env_file: 
      - .dev.env

my Dockerfile in ./app:

FROM kuralabs/python3-dev

WORKDIR /usr/src/app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# RUN pip install --upgrade pip 

COPY ./requirements.txt .
RUN pip3 install -r requirements.txt

COPY . .

My file .dev.env:

ALLOWED_HOSTS='localhost 127.0.0.1'
DEBUG=1
SECRET_KEY='django-insecure-...'

My catalog in attached

I run the project with the commands:

$docker-compose build
$docker-compose up -d

I get variables in settings.py:

load_dotenv()
print(f'Environment: {os.environ}')

my variables from the '.dev.env' file are not in the list of environment variables.

Please help me understand why .dev.env variables don't get into the environment.

1

There are 1 best solutions below

4
YetAnotherDuck On

You can use environment variables from a .env file by assigning them to your service, take the following example

version: '3.9'
services:
  something:
    image: someimage
    container_name: comecontainer
    environment:
      - MARIADB_ROOT_USER
      - MARIADB_ROOT_PASSWORD
      - MARIADB_DATABASE

The environment variables are directly read from the .env file located next to the docker-compose.yaml. Note that env_file still works the same way. So instead of reading from the .env file, you can utilize env_file to target (in your case) the .dev.env file.

Hope this helps.


In addition, perhaps you could assign the path of load_dotenv.

from dotenv import load_dotenv
from pathlib import Path, PurePosixPath

dotenv_path = PurePosixPath(Path(__file__).resolve().parent.parent, '.dev.env').as_posix()
load_dotenv(dotenv_path=dotenv_path)

That should also work, when placed somewhere after your imports in manage.py.