djangodockerdocker-composeenvironment-variables

Docker-compose (and django): Can't get environment variables onto the services


I'm trying to write a small docker(-compose) deployment solution for a small Django application.

Currently, the django-compose file, named docker-compose.dev.yaml looks something like this:

version: "3"

services:
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - 8000:8000
    env_file:
      - dev.env

The file dev.env looks like this:

DEBUG=1
SECRET_KEY=We9ZyuSKsP9Mgvsrt74gExF8baWbGL # not important that this leaks
DJANGO_ALLOWED_HOSTS=localhost

However, when django tries to start, I get the following:

#11 0.634 ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")

#11 0.634 AttributeError: 'NoneType' object has no attribute 'split'

Basically, the environment variable is returning None, meaning the variables aren't getting onto the container.

I tried, according to the docs, to do this:

    # ...
    environment:
      - DEBUG
      - SECRET_KEY
      - DJANGO_ALLOWED_HOSTS

Without any luck.

Any ideas? The repository behind the code is public, I invite you to try.

My current test environment is Docker desktop on Windows 10.


Solution

  • So, I figured it out.

    Turns out that this line in the Dockerfile for the backend:

    RUN python manage.py migrate
    

    Was the problem. I didn't realize it ran at build time, not at runtime, so the environment variables weren't available.

    I moved into a script called at runtime and not it all works!

    backend/Dockerfile:

    # ...
    # Make files executable
    RUN chmod +x start.dev.sh
    

    backend/start.dev.sh:

    #!/bin/bash
    python manage.py migrate
    python manage.py runserver 0.0.0.0:8000
    

    And ./docker-compose.dev.yaml:

    # ...
        command: ./start.dev.sh
    # ...