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 a docker-compose.yml file to define the services for Django and PostgreSQL.
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.
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.
‘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.
psycopg2-binary>=2.8,<3.0
Run Docker Compose:
Use Docker Compose to build and run your containers.
Migrate the Database:
Once the containers are running, apply the migrations to set up your PostgreSQL database.
Create a Superuser (Optional):
Create a Django superuser to access the admin panel.
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.