Django can't read docker enviroment variable

I'm building a docker compose environment and Django can't read the environment variables i try to give it.

Inside my settings.py i have this bit of code

...

import os

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]

DEBUG = os.environ["DEBUG"]

...

and this should be able to read the variables i give to the container, which i tried to give in many different ways. This is the content of my envfile:

DJANGO_SECRET_KEY="k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc"
DEBUG="False"

All of the following result in django not being able to read the variables during docker build.


First attempt: env_file inside compose.yaml

This is my compose.yaml

services:
  django:
    env_file:
      - ./django/.env

Error given: Keyerror


Second attempt: changing env_file path

This is my compose.yaml

services:
  django:
    env_file:
      - /some/other/random/path

Error given: no such file or directory (don't mess around with files that don't exist, the file location is correct)


Third attempt: hardconding variables

This is my compose.yaml

services:
  django:
    environment:
      DJANGO_SECRET_KEY: "k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc"
      DEBUG: "False"
    env_file:
      - ./django/.env

Error given: Keyerror


Fourth attempt: running standalone container

I tried running a docker standalone container and giving the variables by cmd

docker run -dp 127.0.0.1:8000:8000 \
   -e DJANGO_SECRET_KEY='k64dpx9s1h!ijwafy-lif!(*)sabwk*w+rg#6=nu@ty2jkw%gc' \
   -e DEBUG="False" django:v0

Error given: Keyerror


Thanks for reading this far. I hope no one will tell me to use dict.get(key) instead of dict[key] so it won't give me errors, when is better to get a error then a blank or default value.

Back to Top