DEV Community

Cover image for Connect postgres with docker and django
Hitesh Chauhan
Hitesh Chauhan

Posted on

Connect postgres with docker and django

To connect PostgreSQL with Docker and Django, follow these steps:

  1. Set Up Docker and Docker Compose:
    Make sure Docker and Docker Compose are installed on your machine.

  2. Create a Docker Compose File:
    Create a docker-compose.yml file to define the services for Django and PostgreSQL.

version: '3.8'

services:
  db:
    image: postgres:13
    environment:
      POSTGRES_DB: mydatabase
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
    volumes:
      - postgres_data:/var/lib/postgresql/data

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

volumes:
  postgres_data:
Enter fullscreen mode Exit fullscreen mode
  1. Create a Dockerfile for Django: Create a Dockerfile in your Django project root.
# Use the official Python image from the Docker Hub
FROM python:3.9

# Set the working directory in the container
WORKDIR /code

# Copy the requirements file into the container
COPY requirements.txt /code/

# Install the dependencies
RUN pip install -r requirements.txt

# Copy the rest of the application code into the container
COPY . /code/
Enter fullscreen mode Exit fullscreen mode
  1. Configure Django to Use PostgreSQL: Update your settings.py in your Django project to use PostgreSQL.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'db',
        'PORT': '5432',
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Install Dependencies: Make sure your requirements.txt includes the necessary dependencies.
Django>=3.2,<4.0
psycopg2-binary>=2.8,<3.0
Enter fullscreen mode Exit fullscreen mode
  1. Run Docker Compose: Use Docker Compose to build and run your containers.
docker-compose up --build
Enter fullscreen mode Exit fullscreen mode
  1. Migrate the Database: Once the containers are running, apply the migrations to set up your PostgreSQL database.
docker-compose exec web python manage.py migrate
Enter fullscreen mode Exit fullscreen mode
  1. Create a Superuser (Optional): Create a Django superuser to access the admin panel.
docker-compose exec web python manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

Now, you should have a working Django application connected to a PostgreSQL database, both running in Docker containers. You can access your application at http://localhost:8000.

Top comments (0)