[Django]-Missing Environment Vars in docker python:3 with docker-compose

1👍

The RUN is used only when building image. The CMD is the command that is started when you start container from your image. If you run migrate when building image it is wrong, migrate is building your database and you want to run it each time before runserver

# Dockerfile -- api

FROM python:3

RUN pip3 -q install -r requirements.txt
RUN echo `$DJANGO_SECRET_KEY`
CMD /bin/bash -c "python manage.py migrate --settings=falcon.settings.dev-microservice && python manage.py runserver 0.0.0.0:8001 --settings=falcon.settings.dev-microservice"

This is the proper way how to start django in docker, because you want to run the migrations on production when starting server. Not on your PC when building image…

5👍

The environment variables not declared inside the Dockerfile are not visible to the container when building the image. They are only passed to the container at runtime. Since the RUN instruction executes on build, the environment variable DJANGO_SECRET_KEY which is declared outside the Dockerfile won’t be visible to the RUN command.

To solve the issue you can declare the env variable inside the Dockerfile and set it via a build argument:

FROM python:3

RUN pip3 -q install -r requirements.txt
ARG key
ENV DJANGO_SECRET_KEY=$key
RUN echo `$DJANGO_SECRET_KEY`
RUN python manage.py migrate --settings=falcon.settings.dev-microservice
CMD python manage.py runserver 0.0.0.0:8001 --settings=falcon.settings.dev-microservice

Then, you should modify the composefile as such:

build:
  context: /Users/ben/Projects/falcon/falcon-backend
  dockerfile: Dockerfile
  args:
    - key='secrete-key'
👤yamenk

Leave a comment