DEV Community

Micheal Ojemoron
Micheal Ojemoron

Posted on • Updated on

How to Connect your Django App to a dockerized PostgreSQL and pgAdmin

Docker has been my default environment set-up for deploying most of my web projects quickly. It is lightweight and it has also helped me solve package dependencies and environment configuration issues because it provides a consistent environment across different servers and also makes continuous delivery and deployment enjoyable.

Recently, I felt the need to connect my Django application to a dockerized Postgres database and also manage the database with a dockerized pgAdmin(a web app. for managing Postgres databases).

I did this because I wanted my application layer to stay outside the docker environment of my database without the need to install Postgres and pgAdmin on my local machine for a quick app. prototype.
I had several issues setting this up until I successfully got it up and running.
Let me show you how I did it 😊.

In this post, I am assuming that you have successfully installed Docker and Django. I will also be using docker-compose (this will enable you to run multiple containers).
Visit this link to understand what docker-compose is: https://docs.docker.com/compose/

To dockerize Postgres and pgAdmin:

  • create a postgres_docker directory in the root folder that contains your Django project dir.
  • cd into the postgres_docker dir. and create a docker-compose file that will contain the Postgres and pgAdmin images: copy the following code and paste it into your docker-compose file
version: "3.1"

services:

  db:
    restart: always
    image: postgres
    container_name: demo-postgres #you can change this
    environment:
      - POSTGRES_USER=demo
      - POSTGRES_PASS=demo
      - POSTGRES_DB=demo
      - POSTGRES_PORT=5432
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data/

  pgadmin:
      image: dpage/pgadmin4
      container_name: demo-pgadmin #you can change this
      depends_on:
        - db
      ports:
        - "5051:80"
      environment:
        PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin.org
        PGADMIN_DEFAULT_PASSWORD: root
      restart: always


volumes:
  postgres_data:

Enter fullscreen mode Exit fullscreen mode
  • open your command line, cd into postgres_docker dir. and run
docker-compose up
Enter fullscreen mode Exit fullscreen mode

This command builds, (re)creates, starts, and attaches to containers for a service. to confirm if there are no errors, visit http://localhost:5051 to see pgAdmin Interface.

To connect pgAdmin to Postgres:

  • login to pgAdmin with the login details you initialized in the docker-compose file.
 PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin.org #you can change this
 PGADMIN_DEFAULT_PASSWORD: root #you can change this
Enter fullscreen mode Exit fullscreen mode
  • enter the following settings from the images below to your pgAdmin interface Alt text of image Alt text of image Please note
  • your hostname db is the name of your Postgres service in the docker-compose file.

To connect Django to Postgres:

  • In your settings.py, configure database settings like so:
DATABASES = {
    'default': {
        'ENGINE': 'django_postgres_extensions.backends.postgresql',
        'NAME': 'demo',
        'USER': 'demo',
        'HOST': 'localhost',
        'PORT': 5432,
        'PASSWORD':'demo'
    }
}

Enter fullscreen mode Exit fullscreen mode

To see that all went as plan, startup your Django application like so:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

If everything works fine, you should see your application without errors.
visit http://localhost:8000

In conclusion, there are several ways to achieve this but this is my preferred way and it also easy to understand.
If you have any issue with your setup leave your comments below.
Kindly follow me and turn on your notification. Thank you!
Happy coding! ✌

Top comments (12)

Collapse
 
pmutua profile image
Philip Mutua • Edited

Hi Micheal thanks. I have a question I have seen some other examples where one does the following:

volumes:
      - ./data/db:/var/lib/postgresql/data

Enter fullscreen mode Exit fullscreen mode

Based on your example above in the docker-compose.yml file under the db service what is the difference?

Collapse
 
caduceusinc profile image
Wale Opakunle

Micheal, I am not sure exactly how to thank you for this article.
Over the last 24 hours, I have been following articles that use the postgres docker container name as the host while connecting to pgadmin and been unable to connect. 24 hours, and I have been pulling my hair out wondering what the hell I was doing wrong.
Thank you. Thank you so much for sharing your knowledge. I can sleep now.

Collapse
 
laurelgerman profile image
Laurel German

A few notes that may be helpful to other beginners like me:

  • The docker-compose file should be saved as docker-compose.yaml
  • The docker-compose file didn't work as listed, but I changed line 11 to "POSTGRES_PASSWORD=demo" and that worked
  • Change the username/password on lines 27-28 of the docker-compose file to your own email address and a NON-PRIVATE password like "demo" or "password" since you're saving it in plain-text
  • The username and password on lines 27-28 are what you use to log in to pgadmin. The username and password on lines 10-11 are what you enter in the "Connection" tab when you're creating your database.
  • You have to pip install django_postgres_extensions in your django app environment before running runserver, or it won't work
Collapse
 
lewiskori profile image
Lewis kori

This is exactly what I needed. Thank you for sharing

Collapse
 
mojemoron profile image
Micheal Ojemoron • Edited

Thanks, I am glad it helped

Collapse
 
itamar27 profile image
itamar27

Hello, i've been following your instruction but unfortunately I am having some issues which are not mentioned here.

File "C:\Users\Yonatan.virtualenvs\LMS-NZATbBlN\lib\site-packages\django_postgres_extensions\models\expressions.py", line 2, in
from django.utils import six
ImportError: cannot import name 'six' from 'django.utils' (C:\Users\Yonatan.virtualenvs\LMS-NZATbBlN\lib\site-packages\django\utils_init_.py)

This is the error i'm having about some module named "six".

Do you know how to solve this problem?
Haven't found any good answer online

Collapse
 
hemaz88 profile image
Hemaz

Great informations, thanks a lot. I have a question: how can I connect other docker files to Django like what you did with Postgres? I mean how can I connect and consume other model like YoloV5 docker image inside docker?

Collapse
 
rguillermo profile image
Guillermo

Thanks Michael, you saved me a lot of time!

Collapse
 
mojemoron profile image
Micheal Ojemoron

You are welcome Guillermo

Collapse
 
perymerdeka profile image
perymerdeka

how to migrate?

Collapse
 
rdmtinez profile image
Ricardo Martinez

sudo docker exec -it python manage.py migrate
but the django HOST variable in the container must be set to
HOST=db

and if you've bind-mounted your code into the container, you can do it directly from the console in your IDE (e.g. vscode) since the container is sharing the exact same code. BUT here HOST=localhost. This means you have to have separate environment variables set. Confusing, but that's what I've noticed.

Collapse
 
pmutua profile image
Philip Mutua

Hi Micheal, how does one connect to a local MYSQL client using docker compose? If we dont' want to use mysql container?