Docker Compose for Django and PostgreSQL: Setup Guide
docker-compose.yml file to define services for Django and PostgreSQL, linking them with environment variables and volumes. This setup allows Django to connect to PostgreSQL easily inside Docker containers.Syntax
A docker-compose.yml file defines multiple services that run together. For Django and PostgreSQL, you specify:
- services: Defines each container (Django app and PostgreSQL database).
- image: The Docker image to use for each service.
- environment: Variables like database name, user, and password.
- volumes: To persist database data and map code into the container.
- ports: To expose container ports to the host machine.
- depends_on: Ensures Django starts after PostgreSQL is ready.
version: '3.9' services: db: image: postgres:15 environment: POSTGRES_DB: mydb POSTGRES_USER: user POSTGRES_PASSWORD: password volumes: - postgres_data:/var/lib/postgresql/data ports: - "5432:5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - DATABASE_NAME=mydb - DATABASE_USER=user - DATABASE_PASSWORD=password - DATABASE_HOST=db depends_on: - db volumes: postgres_data: {}
Example
This example shows a docker-compose.yml file that runs a Django app connected to a PostgreSQL database. The Django app uses environment variables to connect to the database service named db. The PostgreSQL data is saved on a Docker volume to keep it between restarts.
version: '3.9' services: db: image: postgres:15 environment: POSTGRES_DB: mydb POSTGRES_USER: user POSTGRES_PASSWORD: password volumes: - postgres_data:/var/lib/postgresql/data ports: - "5432:5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - DATABASE_NAME=mydb - DATABASE_USER=user - DATABASE_PASSWORD=password - DATABASE_HOST=db depends_on: - db volumes: postgres_data: {}
Common Pitfalls
1. Wrong database host: Use the service name db as the host in Django settings, not localhost.
2. Missing environment variables: Ensure Django reads the database credentials from environment variables.
3. Database not ready: Django may start before PostgreSQL is ready; use depends_on but consider wait scripts for production.
4. Volume permissions: PostgreSQL data volume must have correct permissions to avoid startup errors.
Wrong example:
web:
environment:
- DATABASE_HOST=localhost
Right example:
web:
environment:
- DATABASE_HOST=dbQuick Reference
Remember these key points when using Docker Compose with Django and PostgreSQL:
- Use
depends_onto order service startup. - Map ports to access services from your machine.
- Use volumes to persist database data.
- Set environment variables for database connection info.
- Use the database service name as the host in Django.