Use PostgreSQL and Django with Docker and Keep Credentials in an .env File

Friday, July 31, 2020
Tags: docker postgresql django

Use this as a starting point: Chapter 2: PostgreSQL | Django For Professionals.

Now define things in an .env file:

POSTGRES_DB=trey_app
POSTGRES_USER=trey_app
POSTGRES_PASSWORD=awesomepassword

The defaults are postgres for all of those, but that’s no fun. Maybe this is more secure? Maybe not. Here’s the documentation for the official Docker image for PostgreSQL. Maybe I can make more sense of that later. I’m just tickled this works now.

Put this block within both the web and the db sections of docker-compose.yml:

environment:
- POSTGRES_DB=${POSTGRES_DB}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

This uses Docker’s default environment stuff.

For db (if I understand correctly), this actually creates that user and database and sets the password. For web, it makes those things available to use in settings.py via the (Docker host’s?) os environment variables. Speaking of which:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('POSTGRES_DB'),
'USER': os.environ.get('POSTGRES_USER'),
'PASSWORD': os.environ.get('POSTGRES_PASSWORD'),
'HOST': 'db',
'PORT': 5432
}
}