# Django + PostgreSQL

> Python Django web framework with PostgreSQL database.

- Category: Full Web Stacks
- Difficulty: intermediate
- Components: django, postgres, nginx
- Tags: django, python, postgres, web-framework
- Source: https://docker.recipes/full-stacks/django-postgres

## Overview

Django is a high-level Python web framework that follows the "batteries-included" philosophy, providing developers with built-in authentication, admin interface, ORM, and security features out of the box. Created in 2005 for newspaper websites, Django has evolved into one of the most popular web frameworks, powering sites like Instagram, Pinterest, and Mozilla. Its emphasis on rapid development, clean pragmatic design, and the DRY (Don't Repeat Yourself) principle makes it ideal for content-heavy applications and complex data-driven websites.

This stack combines Django's robust web framework with PostgreSQL's advanced relational database capabilities and NGINX's high-performance web serving. Django's ORM leverages PostgreSQL's ACID compliance, JSON support, and advanced indexing for complex queries, while NGINX handles static file serving and acts as a reverse proxy to Gunicorn, Django's WSGI server. This architecture separates concerns effectively: NGINX handles HTTP connections and static content, Gunicorn manages Python application processes, and PostgreSQL provides reliable data persistence with advanced features like full-text search and geospatial data support.

This combination is perfect for Python developers building content management systems, e-commerce platforms, social media applications, or any data-intensive web application requiring user authentication and complex database relationships. The stack scales well from prototype to production, with PostgreSQL's replication capabilities and NGINX's load balancing supporting growth from single-server deployments to distributed architectures.

## Features

- Django's built-in admin interface with PostgreSQL's rich data types for complex content management
- PostgreSQL's JSONB support integrated with Django's JSONField for hybrid relational-document data models
- NGINX static file serving with Django's collectstatic management for optimized asset delivery
- Gunicorn WSGI server with multiple worker processes for concurrent request handling
- PostgreSQL's full-text search capabilities accessible through Django's search framework
- NGINX reverse proxy with connection pooling to Gunicorn upstream servers
- Django's migration system leveraging PostgreSQL's transactional DDL for safe schema changes
- PostgreSQL's advanced indexing (GIN, GiST, partial) optimized through Django's database introspection

## Use cases

- Content management systems requiring complex taxonomies and full-text search capabilities
- E-commerce platforms needing ACID-compliant transactions and inventory management
- Social media applications with user-generated content and complex relationship modeling
- Enterprise web applications requiring Django's built-in authentication and permissions system
- Data analytics dashboards leveraging PostgreSQL's window functions and Django's ORM
- Multi-tenant SaaS applications using PostgreSQL's row-level security with Django's middleware
- GIS applications combining Django's GeoDjango with PostgreSQL's PostGIS extension

## Prerequisites

- Docker Engine and Docker Compose installed on host system
- Minimum 1.5GB RAM (512MB for PostgreSQL, 256MB for NGINX, 512MB for Django/Gunicorn, plus OS overhead)
- Python and Django development knowledge for application customization
- PostgreSQL query optimization understanding for production database tuning
- Port 80 available for NGINX HTTP traffic
- Basic understanding of WSGI deployment patterns and Gunicorn configuration

## docker-compose.yml

```yaml
services:
  web:
    build: .
    container_name: django
    command: gunicorn myproject.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - static_volume:/app/staticfiles
    environment:
      DATABASE_URL: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
      SECRET_KEY: ${SECRET_KEY}
    depends_on:
      - postgres
    networks:
      - django

  postgres:
    image: postgres:16-alpine
    container_name: postgres
    environment:
      POSTGRES_DB: ${DB_NAME}
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - django

  nginx:
    image: nginx:alpine
    container_name: nginx
    volumes:
      - static_volume:/app/staticfiles:ro
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
    ports:
      - "80:80"
    depends_on:
      - web
    networks:
      - django

volumes:
  postgres_data:
  static_volume:

networks:
  django:
    driver: bridge
```

## .env

```bash
DB_NAME=django
DB_USER=django
DB_PASSWORD=changeme
SECRET_KEY=your-secret-key
```

## Usage notes

- Docs: https://docs.djangoproject.com/
- Create Dockerfile with Python + gunicorn
- Run migrations: docker compose exec web python manage.py migrate
- Collect static: docker compose exec web python manage.py collectstatic
- Create superuser: docker compose exec web python manage.py createsuperuser
- Configure nginx/nginx.conf to proxy to gunicorn and serve static files

## Troubleshooting

- django.db.utils.OperationalError: could not connect to server: Ensure PostgreSQL container is fully started before Django migrations run
- NGINX 502 Bad Gateway errors: Check that Gunicorn is binding to 0.0.0.0:8000 not localhost:8000 for inter-container communication
- Static files not loading (404 errors): Run 'docker compose exec web python manage.py collectstatic' and verify NGINX volume mount for staticfiles
- PostgreSQL connection pool exhausted: Tune Django's CONN_MAX_AGE setting and PostgreSQL's max_connections parameter based on Gunicorn worker count
- Django migrations hanging: Check PostgreSQL logs for lock conflicts and ensure proper migration ordering in apps
- NGINX upstream timeout errors: Increase proxy_read_timeout in NGINX config for long-running Django views or background tasks

