Joseph Adam
Joseph Adam

Reputation: 1642

docker-compose and django secret key

I have build my postgres and django appplication using the following

version: "3.8"

services:
  django:
    build: .
    container_name: django
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/usr/src/app
    ports:
      - "8000:8000"
    depends_on:
      - db

  db:
    image: postgres
    container_name: pgdb
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

When I check the docker-desktop, I got 2 docker containers, "django" and "pgdb".

When I check the django, it says

django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.

Originally, on my windows 10 machine, I saved the secret key in the windows variable. What is the way to build the docker-compose so it has the secret get?

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

Upvotes: 1

Views: 2336

Answers (1)

HLX Studios
HLX Studios

Reputation: 263

You would need to create a .env file with the SECRET_KEY. In the django_secrets.env you can store like this: SECRET_KEY=my_secret_key

Then in the docker-compose.yml file you can specify the django_secrets.env file:

version: "3.8"

services:
  django:
    build: .
    container_name: django
    command: python manage.py runserver 0.0.0.0:8000
    env_file:
        - ./django_secrets.env
    volumes:
      - .:/usr/src/app
    ports:
      - "8000:8000"
    depends_on:
      - db

  db:
    image: postgres
    container_name: pgdb
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

And then you can get the value in the settings.py file like this:

SECRET_KEY = os.environ.get("SECRET_KEY", 'my_default_secret_key')

You can have the django_secrets.env file in any path, you just need to specify the path in the docker-compose.yml file. Also you can name it as you like

Upvotes: 3

Related Questions