Hitesh Chauhan
Posted on August 8, 2024
To connect PostgreSQL with Docker and Django, follow these steps:
Set Up Docker and Docker Compose:
Make sure Docker and Docker Compose are installed on your machine.Create a Docker Compose File:
Create adocker-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:
-
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/
-
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',
}
}
-
Install Dependencies:
Make sure your
requirements.txt
includes the necessary dependencies.
Django>=3.2,<4.0
psycopg2-binary>=2.8,<3.0
- Run Docker Compose: Use Docker Compose to build and run your containers.
docker-compose up --build
- 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
- Create a Superuser (Optional): Create a Django superuser to access the admin panel.
docker-compose exec web python manage.py createsuperuser
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
.
💖 💪 🙅 🚩
Hitesh Chauhan
Posted on August 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.