# Production Django Stack

> ready Django with Nginx, Gunicorn, PostgreSQL, Redis, and Celery for async tasks

- Category: Full Web Stacks
- Difficulty: advanced
- Components: nginx, django, gunicorn, postgres, redis, celery
- Tags: django, python, production, celery, nginx, postgres, redis
- Source: https://docker.recipes/full-stacks/production-django-stack

## Overview

Django is a high-level Python web framework that follows the model-template-view architectural pattern, originally developed at Lawrence Journal-World newspaper in 2003 and open-sourced in 2005. Known for its 'batteries included' philosophy, Django provides built-in admin interface, ORM, authentication, and security features that enable rapid development of secure, maintainable web applications. This production stack combines Django with Gunicorn as the WSGI server, NGINX as the reverse proxy, PostgreSQL for robust data persistence, Redis for caching and message brokering, and Celery for distributed task processing.

This architecture addresses the core challenges of running Django applications at scale: NGINX handles static file serving and SSL termination while reverse proxying dynamic requests to Gunicorn workers, PostgreSQL provides ACID-compliant data storage with advanced querying capabilities, Redis serves dual roles as Django's cache backend and Celery's message broker, while Celery workers process time-intensive tasks asynchronously to prevent request timeouts. The inclusion of Celery Beat enables scheduled task execution, making this stack suitable for applications requiring background job processing, periodic data synchronization, and email sending.

This configuration is ideal for startups moving from development to production, established companies deploying content management systems, e-commerce platforms, or SaaS applications that require reliable background task processing. The stack provides the horizontal scaling capabilities needed for growing user bases while maintaining the development velocity that makes Django attractive to Python teams.

## Features

- Gunicorn WSGI server with configurable worker processes for handling concurrent Django requests
- NGINX reverse proxy with static file serving and request buffering for improved performance
- PostgreSQL ACID-compliant database with JSON support and full-text search capabilities
- Redis dual-purpose deployment serving as Django cache backend and Celery message broker
- Celery distributed task queue with separate worker containers for background job processing
- Celery Beat scheduler for periodic task execution and cron-like job scheduling
- Multi-container architecture enabling independent scaling of web workers and task processors
- Shared volume mounts for Django static files and media uploads across containers

## Use cases

- Content management systems requiring image processing and thumbnail generation
- E-commerce platforms with order processing, inventory updates, and email notifications
- SaaS applications needing user onboarding workflows and scheduled data exports
- News or blog sites with search indexing and scheduled content publication
- Financial applications requiring background report generation and data aggregation
- Social platforms with notification systems and periodic cleanup tasks
- Multi-tenant applications requiring tenant-specific background processing

## Prerequisites

- Minimum 2GB RAM to accommodate PostgreSQL (1GB), Redis (512MB), and multiple Python processes
- Port 80 available for NGINX HTTP traffic (configurable via NGINX_PORT environment variable)
- Django application with properly configured settings.py for database and Redis connections
- Understanding of Celery task decorators and Django's collectstatic command
- Familiarity with Gunicorn worker configuration and Django WSGI deployment
- Basic knowledge of PostgreSQL user management and database creation

## docker-compose.yml

```yaml
services:
  nginx:
    image: nginx:alpine
    container_name: django-nginx
    restart: unless-stopped
    ports:
      - "${NGINX_PORT:-80}:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./static:/app/static:ro
      - ./media:/app/media:ro
    depends_on:
      - web

  web:
    build:
      context: ./app
      dockerfile: Dockerfile
    container_name: django-web
    restart: unless-stopped
    command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 --workers 4
    volumes:
      - ./app:/app
      - ./static:/app/static
      - ./media:/app/media
    environment:
      - DEBUG=${DEBUG:-False}
      - SECRET_KEY=${SECRET_KEY}
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379/0
      - CELERY_BROKER_URL=redis://redis:6379/1
    depends_on:
      - db
      - redis

  celery:
    build:
      context: ./app
      dockerfile: Dockerfile
    container_name: django-celery
    restart: unless-stopped
    command: celery -A config worker -l info
    volumes:
      - ./app:/app
    environment:
      - DEBUG=${DEBUG:-False}
      - SECRET_KEY=${SECRET_KEY}
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379/0
      - CELERY_BROKER_URL=redis://redis:6379/1
    depends_on:
      - db
      - redis

  celery-beat:
    build:
      context: ./app
      dockerfile: Dockerfile
    container_name: django-celery-beat
    restart: unless-stopped
    command: celery -A config beat -l info
    volumes:
      - ./app:/app
    environment:
      - DEBUG=${DEBUG:-False}
      - SECRET_KEY=${SECRET_KEY}
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - CELERY_BROKER_URL=redis://redis:6379/1
    depends_on:
      - celery

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

  redis:
    image: redis:7-alpine
    container_name: django-redis
    restart: unless-stopped
    volumes:
      - redis_data:/data

volumes:
  postgres_data:
  redis_data:
```

## .env

```bash
# Django Production Stack
NGINX_PORT=80
DEBUG=False

# Security
SECRET_KEY=your-super-secret-key-change-in-production

# Database
DB_USER=django
DB_PASSWORD=django_password
DB_NAME=django_db
```

## Usage notes

- Create ./app/Dockerfile with your Django app
- Configure nginx.conf for static files and proxy
- Run migrations: docker compose exec web python manage.py migrate
- Collect static: docker compose exec web python manage.py collectstatic
- Celery handles async tasks, beat handles scheduled tasks
- Scale workers: docker compose up -d --scale celery=3

## Troubleshooting

- 502 Bad Gateway from NGINX: Check if Gunicorn is running on port 8000 and web container is healthy
- Celery workers not processing tasks: Verify CELERY_BROKER_URL points to Redis and tasks are properly registered
- Static files not loading: Run 'docker compose exec web python manage.py collectstatic' and check NGINX volume mounts
- PostgreSQL connection refused: Ensure DATABASE_URL environment variable matches POSTGRES_* settings in db service
- High memory usage: Reduce Gunicorn workers from 4 to 2-3 or implement connection pooling for PostgreSQL
- Celery Beat duplicate tasks: Only run one celery-beat container and check for proper task scheduling configuration

