Production Deployment Guide

This guide covers deploying the NSGG Backend to a production environment.

Prerequisites

  • Docker and Docker Compose
  • PostgreSQL 15+
  • Redis 7+
  • Domain name and SSL certificate
  • Cloud provider account (AWS/GCP/Azure)

Environment Setup

  1. Set up environment variables:
# .env.production
DEBUG=False
ALLOWED_HOSTS=api.yourdomain.com
DATABASE_URL=postgres://user:password@host:5432/nsgg
REDIS_URL=redis://host:6379/0
SECRET_KEY=your-secure-secret-key
STRIPE_PUBLIC_KEY=your-stripe-public-key
STRIPE_SECRET_KEY=your-stripe-secret-key
STRIPE_WEBHOOK_SECRET=your-stripe-webhook-secret
  1. Configure SSL certificates:
  2. Obtain SSL certificate from Let's Encrypt or your provider
  3. Configure certificate paths in Nginx

Database Setup

  1. Create production database:
CREATE DATABASE nsgg;
CREATE USER nsgg_user WITH PASSWORD 'secure_password';
GRANT ALL PRIVILEGES ON DATABASE nsgg TO nsgg_user;
  1. Configure database backups:
    # /etc/cron.daily/backup-nsgg-db
    #!/bin/bash
    pg_dump -U nsgg_user nsgg | gzip > /backup/nsgg-$(date +%Y%m%d).sql.gz
    

Docker Configuration

  1. Production Dockerfile:
FROM python:3.12-slim

ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1

WORKDIR /app

RUN apt-get update && apt-get install -y \
    postgresql-client \
    && rm -rf /var/lib/apt/lists/*

COPY requirements/production.txt .
RUN pip install --no-cache-dir -r production.txt

COPY . .

RUN python manage.py collectstatic --noinput

CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000"]
  1. Docker Compose for production:
version: '3.8'

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - DATABASE_URL=${DATABASE_URL}
      - REDIS_URL=${REDIS_URL}
    ports:
      - "8000:8000"
    depends_on:
      - redis

  redis:
    image: redis:7-alpine
    volumes:
      - redis_data:/data

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx:/etc/nginx/conf.d
      - ./static:/static
      - ./media:/media
      - /etc/letsencrypt:/etc/letsencrypt
    depends_on:
      - web

volumes:
  redis_data:

Nginx Configuration

# /etc/nginx/conf.d/nsgg.conf
upstream nsgg_backend {
    server web:8000;
}

server {
    listen 80;
    server_name api.yourdomain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name api.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/api.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.yourdomain.com/privkey.pem;

    location / {
        proxy_pass http://nsgg_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /static/ {
        alias /static/;
        expires 1d;
        add_header Cache-Control "public, no-transform";
    }

    location /media/ {
        alias /media/;
        expires 1d;
        add_header Cache-Control "public, no-transform";
    }
}

Deployment Steps

  1. Build and deploy:
# Build images
docker-compose -f docker-compose.prod.yml build

# Start services
docker-compose -f docker-compose.prod.yml up -d

# Run migrations
docker-compose -f docker-compose.prod.yml exec web python manage.py migrate
  1. Set up monitoring:
# Install Prometheus and Grafana
helm install prometheus prometheus-community/prometheus
helm install grafana grafana/grafana
  1. Configure backups:
# Set up database backups
chmod +x /etc/cron.daily/backup-nsgg-db

# Set up media backups
aws s3 sync /path/to/media s3://your-bucket/media/

Security Checklist

  1. SSL/TLS Configuration:
  2. Enable SSL
  3. Configure secure ciphers
  4. Enable HSTS

  5. Firewall Rules:

  6. Allow ports 80, 443
  7. Restrict SSH access
  8. Configure rate limiting

  9. Database Security:

  10. Regular backups
  11. Encrypted connections
  12. Strong passwords

  13. Application Security:

  14. Enable CSRF protection
  15. Set secure cookie flags
  16. Configure CORS properly

Monitoring

  1. Set up Prometheus metrics:
# settings.py
INSTALLED_APPS += ['django_prometheus']

MIDDLEWARE = ['django_prometheus.middleware.PrometheusBeforeMiddleware'] + MIDDLEWARE
MIDDLEWARE += ['django_prometheus.middleware.PrometheusAfterMiddleware']
  1. Configure Grafana dashboards:
  2. Request latency
  3. Error rates
  4. Database performance
  5. Cache hit rates

Maintenance

  1. Database maintenance:

    # Vacuum database
    docker-compose exec db psql -U nsgg_user -d nsgg -c "VACUUM ANALYZE;"
    

  2. Log rotation:

    /var/log/nsgg/*.log {
        daily
        rotate 14
        compress
        delaycompress
        notifempty
        create 0640 www-data www-data
        sharedscripts
        postrotate
            [ ! -f /var/run/nginx.pid ] || kill -USR1 `cat /var/run/nginx.pid`
        endscript
    }
    

Troubleshooting

  1. Check logs:

    docker-compose logs -f web
    

  2. Monitor resources:

    docker stats
    

  3. Check database connections:

    SELECT * FROM pg_stat_activity;
    

Scaling

  1. Horizontal scaling:
  2. Add web servers
  3. Configure load balancer
  4. Scale Redis cluster

  5. Vertical scaling:

  6. Increase resources
  7. Optimize queries
  8. Implement caching

Rollback Procedure

  1. Tag releases:

    git tag v1.0.0
    

  2. Rollback steps:

    # Switch to previous version
    git checkout v1.0.0
    
    # Rebuild and restart
    docker-compose -f docker-compose.prod.yml up -d --build