Dockerize Django PostgreSQL — Simple Set-Up using Docker Compose

This is a simple guide to set up a Django - PostgreSQL app. So, we don’t need to install the PostgreSQL in your device, the docker-compose will take care of that.

Before we start I consider you have already:

  1. Created a Django Project with default/your configs and it’s running.
  2. Installed Docker Engine & docker-compose in your device.

If you’re having any issue in doing these initial setup, let me know in comments. I’ll try to help you out with the prerequisites as well.

Okay, we’ll be required to follow these simple steps:

  1. Create a Dockerfile
  2. Install python dependencies (we can use requirements.txt)
  3. Create a docker-compose.yml file
  4. Modify python file to add PostgreSQL DB Config.

Let’s start doing then …

Create a Dockerfile

FROM python:3
COPY requirements.txt /code/
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
COPY . /code/

In this Dockerfile, we are starting with a Python 3 parent image(You can modify according to your project requirements). Then we’re adding a new code directory where your project code will be copied and used by the container. We are modifying the parent image further by installing the Python dependencies defined in the requirements.txt file.

Add required libraries in requirements.txt


If you don’t know about requirements.txt file, then here’s the guide.

Docker Compose Configurations

version: '3'

build: .
command: python runserver
- .:/code
- "8000:8000"
- postgres
image: postgres
- POSTGRES_DB=postgres
- POSTGRES_USER=postgres

This configuration defines two services: The web service of your app and the postgres service of your database. You can modify the configuration fields anytime, here’s a manual for working with docker-compose file.

Add DB Settings in Django File

'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'postgres',
'PORT': '5432',

We have made all the required changes. Now it’s time to test your application.

Run the project using docker-compose Command

Run the command …

sudo docker-compose up --build

You’ll be seeing lots of build logs and at the end something like …

web_1 | Django version 2.2.5, using settings 'mydemoapp.settings'
web_1 | Starting development server at
web_1 | Quit the server with CONTROL-C.

That means, your Django app is running at the port 8000 on your Docker host. Go to http://localhost:8000 on a web browser to see the Django app home page.

Hurray …! You just finished the setup of a Django app that uses Postgresql DB using a Docker Host.

Thanks for reading this guide! Add an 👏🏻 [clap] if it was helpful. Leave a comment below if you have any questions. Make sure to check my other Medium blogs and connect with me on LinkedIn for more interesting discussions.

Happy Coding ❤