Home > Article > Backend Development > Connect postgres with docker and django
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.
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:
# 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/
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'db', 'PORT': '5432', } }
Django>=3.2,<4.0 psycopg2-binary>=2.8,<3.0
docker-compose up --build
docker-compose exec web python manage.py migrate
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.
The above is the detailed content of Connect postgres with docker and django. For more information, please follow other related articles on the PHP Chinese website!