Authenticating Django PostgreSQL User in Multiple Docker Compose Environments

I’ve been building a Django project template using Docker Compose, PostgreSQL, and Nginx. Docker is a definite weak point for me, so I used an article from Michael Herman to set it up: Dockerizing Django with Postgres, Gunicorn, and Nginx.

I made some additions to that tutorial – custom user model, re-organized config files – but I kept running into the same issue…

Django Can’t Connect to Postgres

When switching between development and production environments, Django could not connect to my postgres database:

docker-compose up -d --build
docker-compose exec web python manage.py migrate

django.db.utils.OperationalError: FATAL: password authentication failed for user "<USERNAME>"

I had set up the same username for both the development and the production environment postgres services, but the passwords were different. For some reason, Docker Compose wasn’t re-configuring postgres with the new information when I switched containers.

Temporary Fix

I was able to avoid the problem with some help from the testdriven.io tutorial mentioned above:

docker-compose down -v
docker-compose -f docker-compose.prod.yml down -v

The -v flag brings down all volumes, i.e. my postgres database. Then, when bringing the containers back up, Docker Compose would say, “I don’t have any volume called postgres_data. I better make one!”

This would totally work, but I would lose any data that I’d put in postgres. In the long term, this will prove to be a headache.

More Permanent Fix

I decided to give each postgres database service it’s own name in my docker-compose.yml and docker-compose.prod.yml files. Instead of postgres_data, I used postgres_data_dev and postgres_data_prod.

But wait!

In this process, I received the following warning:

docker-compose up

WARNING: Service "db" is using volume "/var/lib/postgresql/data" from the previous container.

I had taken down the containers, but since I hadn’t removed them, changing docker-compose.yml tried to use the same part of my filesystem.

To fix, I removed the volumes:

docker-compose down -v

I also heard something about orphan containers. The warning in the command line will help you solve that.

Featured Image Photo Credit: Jeff Kubina, unmodified (CC BY-SA 2.0)

Get Notified of New Posts

Sign up for the newsletter and I'll send you an email when there's a new post.