Django ships with most of what a production site needs, but deploying it still means getting several things right: the application server, database connections, static files, security settings and background work.

The short answer: Django runs in production under Gunicorn, behind Nginx, on any Ubuntu server. Gunicorn runs your app on a local port, Nginx handles HTTPS and static files (or WhiteNoise serves them), PostgreSQL stores the data, and a systemd service starts Gunicorn on boot and restarts it if it crashes.

This guide walks through that setup in order: server packages, production settings, Gunicorn, systemd, Nginx and a Let’s Encrypt certificate. After that come the optional parts (Celery, Redis caching, WebSockets), a GitHub Actions pipeline that tests and then deploys over SSH, common errors, and a launch checklist. If you are still choosing a server, see this post on hosting options for AI-built apps. If you would rather have an AI agent run the deployment, skip to the section on that.

What a Django Production Setup Needs

Django applications have deployment needs that differ from simple static sites:

  • WSGI/ASGI server: Gunicorn for WSGI apps, Daphne or Uvicorn for WebSockets
  • Database: PostgreSQL, MySQL, or another supported backend
  • Static files: collected with collectstatic and served by Nginx, WhiteNoise or a CDN
  • Media files: user uploads, on local disk or in object storage such as S3
  • Background tasks: Celery workers, if you send email or process files outside the request cycle
  • Caching: Redis or Memcached, if you need it
  • Security settings: DEBUG = False, HTTPS, secure cookies, a secret key kept out of the repo

Prepare the Server

These commands assume Ubuntu 22.04 or 24.04 and a sudo user. Replace myuser, mydb, yourdomain.com and the repository URL.

sudo apt update
sudo apt install -y python3-venv python3-dev build-essential libpq-dev nginx postgresql certbot python3-certbot-nginx

# Only if you use Redis for caching or Celery
sudo apt install -y redis-server

# Database and user
sudo -u postgres psql -c "CREATE USER myuser WITH PASSWORD 'change-me';"
sudo -u postgres psql -c "CREATE DATABASE mydb OWNER myuser;"

# Application code and virtualenv
sudo mkdir -p /var/www/django-app
sudo chown $USER:$USER /var/www/django-app
git clone https://github.com/yourusername/django-app.git /var/www/django-app
cd /var/www/django-app
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt gunicorn "psycopg[binary]" dj-database-url
mkdir -p logs

Keep secrets in an environment file next to the code, never in git. systemd reads this file for the service, so use plain KEY=value lines with no export:

# /var/www/django-app/.env
DJANGO_SETTINGS_MODULE=myproject.settings.production
SECRET_KEY=generate-a-long-random-value
DATABASE_URL=postgres://myuser:change-me@localhost:5432/mydb
REDIS_URL=redis://127.0.0.1:6379/1
chmod 600 /var/www/django-app/.env

For backups, replication and tuning beyond this basic setup, the separate PostgreSQL hosting guide goes further.

Production Django Settings

# settings/production.py
import os
from .base import *
import dj_database_url

# Security
DEBUG = False
ALLOWED_HOSTS = [
    'yourdomain.com',
    'www.yourdomain.com',
]

SECRET_KEY = os.environ['SECRET_KEY']

# Database (reads DATABASE_URL from the environment)
DATABASES = {
    'default': dj_database_url.config(
        conn_max_age=600,
        conn_health_checks=True,
    )
}

# HTTPS settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')  # Nginx sets this header
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

# Cookies and sessions
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_AGE = 86400  # 1 day
CSRF_COOKIE_HTTPONLY = True
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'

# Static and media files
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Cache (built into Django 4.0 and newer, needs the redis package)
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379/1'),
    }
}

# Celery (only if you run workers)
CELERY_BROKER_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379/0')
CELERY_RESULT_BACKEND = os.environ.get('REDIS_URL', 'redis://localhost:6379/0')
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'

# Email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.environ.get('EMAIL_HOST')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
DEFAULT_FROM_EMAIL = 'noreply@yourdomain.com'

# Logging: write to stdout, systemd stores it in the journal
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.environ.get('DJANGO_LOG_LEVEL', 'INFO'),
            'propagate': False,
        },
    },
}

Three notes on this file. SECURE_PROXY_SSL_HEADER is what stops SECURE_SSL_REDIRECT from looping forever behind Nginx, so keep them together. SECURE_BROWSER_XSS_FILTER was removed in Django 4.0 and modern browsers ignore the old X-XSS-Protection header, so neither appears here. If you use Django 4.2 or older, STATICFILES_STORAGE still works, but newer versions use the STORAGES setting shown in the static files section.

Run the First Release

Load the same variables in your shell, then run the one-time commands:

cd /var/www/django-app
source venv/bin/activate
set -a; source .env; set +a

python manage.py check --deploy
python manage.py collectstatic --noinput
python manage.py migrate
python manage.py createsuperuser   # optional

sudo chown -R www-data:www-data /var/www/django-app
sudo chmod -R 755 /var/www/django-app
sudo chmod 600 /var/www/django-app/.env

check --deploy prints warnings for any security setting that is still at its default. Fix those before you go live.

Gunicorn Configuration

# gunicorn.conf.py
import multiprocessing

bind = "127.0.0.1:8000"
workers = multiprocessing.cpu_count() * 2 + 1
max_requests = 1000
max_requests_jitter = 50
preload_app = True
timeout = 30
keepalive = 2

# Logging
errorlog = "/var/www/django-app/logs/gunicorn_error.log"
accesslog = "/var/www/django-app/logs/gunicorn_access.log"
loglevel = "info"

proc_name = 'django-app'

Gunicorn binds to 127.0.0.1, so only Nginx on the same machine can reach it. max_requests restarts each worker after a set number of requests, which limits the damage from slow memory growth. workers = cpu_count * 2 + 1 is a common starting point, but on a small server with 1 or 2 GB of RAM, check memory use and lower it if needed.

Systemd Service

sudo tee /etc/systemd/system/django-app.service > /dev/null <<'EOF'
[Unit]
Description=Django App Gunicorn daemon
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/django-app
Environment="PATH=/var/www/django-app/venv/bin"
EnvironmentFile=/var/www/django-app/.env
ExecStart=/var/www/django-app/venv/bin/gunicorn --config gunicorn.conf.py myproject.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable --now django-app
sudo systemctl status django-app

If the service fails, read the reason with sudo journalctl -u django-app -n 50. After a code deploy, use sudo systemctl restart django-app. A reload (HUP) does not pick up new code while preload_app = True.

Nginx Configuration

Start with an HTTP-only site. Certbot adds the HTTPS block and the redirect in the next step, which avoids pointing Nginx at certificate files that do not exist yet.

sudo tee /etc/nginx/sites-available/django-app > /dev/null <<'EOF'
upstream django_backend {
    server 127.0.0.1:8000 fail_timeout=0;
}

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    client_max_body_size 50M;

    # Static files
    location /static/ {
        alias /var/www/django-app/staticfiles/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Media files
    location /media/ {
        alias /var/www/django-app/media/;
        expires 30d;
        add_header Cache-Control "public";
    }

    # Main application
    location / {
        proxy_pass http://django_backend;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # Health check
    location /health/ {
        access_log off;
        proxy_pass http://django_backend;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
    }
}
EOF

sudo ln -s /etc/nginx/sites-available/django-app /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default

sudo nginx -t
sudo systemctl reload nginx

Nginx stays in front for three reasons. It terminates TLS, it serves static and media files without touching Python, and it buffers slow clients so they do not tie up Gunicorn workers.

HTTPS with Let’s Encrypt

Point your domain’s DNS at the server first, then run Certbot:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

# The Ubuntu package installs a renewal timer. Confirm renewal works:
sudo certbot renew --dry-run

Run Certbot before you test in a browser. With SECURE_SSL_REDIRECT = True, Django redirects every plain HTTP request to HTTPS, and that redirect will fail until the certificate exists.

Celery Workers (Optional)

Only add these if your app has tasks that should run outside the request cycle. Celery needs a broker, which is Redis in this guide.

sudo tee /etc/systemd/system/celery-worker.service > /dev/null <<'EOF'
[Unit]
Description=Celery Worker Service
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/django-app
Environment="PATH=/var/www/django-app/venv/bin"
EnvironmentFile=/var/www/django-app/.env
ExecStart=/var/www/django-app/venv/bin/celery -A myproject worker --loglevel=info
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

sudo tee /etc/systemd/system/celery-beat.service > /dev/null <<'EOF'
[Unit]
Description=Celery Beat Service
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/django-app
Environment="PATH=/var/www/django-app/venv/bin"
EnvironmentFile=/var/www/django-app/.env
ExecStart=/var/www/django-app/venv/bin/celery -A myproject beat --loglevel=info
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable --now celery-worker celery-beat

Run celery beat as a single instance only. Two copies would queue every scheduled task twice. Logs go to the journal: sudo journalctl -u celery-worker -f.

# myproject/celery.py
import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.production')

app = Celery('myproject')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
# myproject/__init__.py
from .celery import app as celery_app

__all__ = ('celery_app',)
# myapp/tasks.py
from celery import shared_task
from celery.utils.log import get_task_logger
from django.core.mail import send_mail

logger = get_task_logger(__name__)

@shared_task(bind=True, max_retries=3)
def send_email_task(self, subject, message, recipient_list):
    try:
        send_mail(subject, message, 'noreply@yourdomain.com', recipient_list, fail_silently=False)
        return True
    except Exception as exc:
        logger.error("Email sending failed: %s", exc)
        raise self.retry(exc=exc, countdown=60 * (self.request.retries + 1))

If you later route tasks to named queues, start the worker with -Q queue1,queue2. A worker only consumes the queues it is told about, and tasks sent to any other queue wait forever.

Database Connections and Migrations

Connection pooling

Every Gunicorn worker opens its own database connection. With the default PostgreSQL limit of 100 connections, a large worker count plus Celery can run into that limit. The simplest fix is persistent connections (conn_max_age=600, already set above). On Django 5.1 or newer with psycopg 3, Django also has built-in connection pooling:

# pip install "psycopg[binary,pool]"
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASSWORD'],
        'HOST': os.environ.get('DB_HOST', 'localhost'),
        'PORT': os.environ.get('DB_PORT', '5432'),
        'OPTIONS': {
            'pool': True,
        },
    }
}

For many app servers, a separate pooler such as PgBouncer is the usual next step.

Running migrations safely

Take a backup first, then migrate:

sudo -u postgres pg_dump mydb | gzip > ~/mydb-$(date +%F-%H%M).sql.gz
python manage.py migrate --noinput

Test restoring a backup at least once on another machine, because an untested backup is a guess. For changes that must not break the running version, split them into steps: add a nullable column first, deploy code that uses it, and drop old columns in a later release.

Static and Media Files

Run python manage.py collectstatic --noinput on every deploy so STATIC_ROOT holds the current files. After that you have two options.

Nginx serves them. This is the setup above: the /static/ location points at STATIC_ROOT, and Python never sees those requests.

WhiteNoise serves them from Gunicorn. This removes the Nginx static location and is handy when you have no control over the web server config:

# pip install whitenoise
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',  # directly after SecurityMiddleware
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ... other middleware
]

# Django 4.2 and newer
STORAGES = {
    'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage'},
    'staticfiles': {'BACKEND': 'whitenoise.storage.CompressedManifestStaticFilesStorage'},
}

WhiteNoise handles static files only. User uploads in MEDIA_ROOT still need Nginx or object storage.

S3 storage for media files

If you run more than one server, or want uploads off the local disk, store media in S3 with django-storages:

# settings/production.py
# pip install django-storages boto3
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME')
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# Credentials: prefer an IAM role on the server. Otherwise set
# AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the environment.

STORAGES = {
    'default': {'BACKEND': 'storage_backends.MediaStorage'},
    'staticfiles': {'BACKEND': 'whitenoise.storage.CompressedManifestStaticFilesStorage'},
}
# storage_backends.py
from storages.backends.s3 import S3Storage

class MediaStorage(S3Storage):
    location = 'media'
    default_acl = None      # new S3 buckets block ACLs by default
    file_overwrite = False

Caching

Django has a built-in Redis cache backend (configured in the settings above), and the cache API works the same on every backend.

from django.core.cache import cache
from django.views.decorators.cache import cache_page

# Cache a computed value for five minutes
def get_stats():
    return cache.get_or_set('site_stats', compute_stats, timeout=300)

# Cache a whole public page for fifteen minutes
@cache_page(60 * 15)
def pricing_page(request):
    ...

Do not cache pages that differ per user. cache_page varies on the headers a response lists in Vary, but a page that shows account details should not be cached at the view level at all. The Redis caching guide covers eviction, memory limits and persistence.

WebSockets with Django Channels

Gunicorn’s sync workers do not handle WebSockets. If you use Channels, run the ASGI app under Daphne (or Uvicorn) as a second service, and send /ws/ traffic to it from Nginx.

# asgi.py
import os
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.production')
django_asgi_app = get_asgi_application()  # must run before importing routing

from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
import myapp.routing

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(URLRouter(myapp.routing.websocket_urlpatterns))
    ),
})
# settings/production.py
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {'hosts': [os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379/2')]},
    }
}
# Run as its own systemd service, same pattern as Gunicorn
daphne -b 127.0.0.1 -p 8001 myproject.asgi:application
location /ws/ {
    proxy_pass http://127.0.0.1:8001;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Security

Most of Django’s protection comes from its defaults and the settings above. Beyond those:

# Report settings that are still unsafe for production
python manage.py check --deploy

# Firewall: only SSH and web traffic
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
  • Keep SECRET_KEY, database passwords and API keys in the environment file, not in git.
  • Keep PostgreSQL and Redis bound to localhost. Neither needs to be reachable from the internet in this setup.
  • Rate limit login and API paths in Nginx with limit_req_zone and limit_req, rather than inside Django. Nginx rejects the traffic before it uses a Gunicorn worker.
  • Run pip list --outdated or a tool such as pip-audit on a schedule, and apply Django security releases promptly.

Query Performance

Slow pages are usually slow queries. Fetch related rows in bulk instead of one query per row:

from django.db.models import Prefetch
from myapp.models import User

def get_user_with_related(user_id):
    return (
        User.objects
        .select_related('profile')
        .prefetch_related(
            'posts__comments',
            Prefetch('followers', queryset=User.objects.only('id', 'username')),
        )
        .get(id=user_id)
    )

Use select_related for single-valued relations (foreign keys) and prefetch_related for many-valued ones. Add indexes for columns you filter or order by often, and check suspect queries with EXPLAIN ANALYZE in psql.

Health Checks and Logs

A small view gives Nginx, a load balancer or an uptime monitor something to poll:

# views.py
from django.db import connection
from django.http import JsonResponse

def health_check_view(request):
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
    except Exception:
        return JsonResponse({'status': 'unhealthy'}, status=503)
    return JsonResponse({'status': 'healthy'})

Route it at /health/ to match the Nginx location above. Application logs are in journalctl -u django-app, and Gunicorn’s own logs are in the logs/ directory. Add an error tracker such as Sentry so you hear about exceptions before users report them.

CI/CD with GitHub Actions

This workflow runs your tests on every push and pull request, then deploys to your server over SSH when tests pass on main. Add SSH_HOST, SSH_USER and SSH_KEY (a private key dedicated to deploys) as repository secrets.

# .github/workflows/django-deploy.yml
name: Test and deploy Django

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: postgres
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'
          cache: 'pip'

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Run tests
        run: python manage.py test
        env:
          # A settings module for CI that reads DATABASE_URL
          DJANGO_SETTINGS_MODULE: myproject.settings.ci
          DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres
          SECRET_KEY: ci-only-secret-key

  deploy:
    needs: test
    runs-on: ubuntu-latest
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'

    steps:
      - uses: actions/checkout@v4

      - name: Set up SSH
        env:
          SSH_HOST: ${{ secrets.SSH_HOST }}
          SSH_KEY: ${{ secrets.SSH_KEY }}
        run: |
          mkdir -p ~/.ssh
          echo "$SSH_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts

      - name: Copy code to the server
        env:
          SSH_HOST: ${{ secrets.SSH_HOST }}
          SSH_USER: ${{ secrets.SSH_USER }}
        run: |
          rsync -az --delete \
            --exclude '.git' --exclude '.env' --exclude 'venv' \
            --exclude 'media' --exclude 'staticfiles' --exclude 'logs' \
            ./ "$SSH_USER@$SSH_HOST:/var/www/django-app/"

      - name: Install, migrate and restart
        env:
          SSH_HOST: ${{ secrets.SSH_HOST }}
          SSH_USER: ${{ secrets.SSH_USER }}
        run: |
          ssh "$SSH_USER@$SSH_HOST" '
            set -e
            cd /var/www/django-app
            set -a; . ./.env; set +a
            venv/bin/pip install -r requirements.txt
            venv/bin/python manage.py migrate --noinput
            venv/bin/python manage.py collectstatic --noinput
            sudo systemctl restart django-app
          '

The SSH user must be able to write to /var/www/django-app and to run sudo systemctl restart django-app without a password (a sudoers rule limited to that command works). Set both up before the first run. ssh-keyscan trusts whatever key the host presents on first contact, so for stricter setups store the server’s known host key as a secret instead. A restart drops in-flight requests for a moment. If that matters, run two instances behind Nginx and restart them one at a time.

Common Django Deployment Problems

  • Static files return 404. Check that collectstatic ran, that STATIC_ROOT matches the Nginx alias path, and that the www-data user can read the directory. With WhiteNoise, check the middleware order.
  • 502 Bad Gateway. Gunicorn is not running or not on port 8000. Check sudo systemctl status django-app and sudo journalctl -u django-app -n 50.
  • 400 Bad Request. The domain is missing from ALLOWED_HOSTS, or Nginx is not passing the Host header.
  • Endless redirect to HTTPS. SECURE_PROXY_SSL_HEADER is missing, or Nginx does not send X-Forwarded-Proto.
  • too many connections from PostgreSQL. Workers times connections per worker is above the database limit. Lower the worker count, use persistent connections or pooling, or add PgBouncer.
  • Workers use more memory over time. Keep max_requests set in gunicorn.conf.py so workers are recycled, and look for large objects held in module-level variables.

Django Deployment Checklist

Before deploying

  • DEBUG = False
  • SECRET_KEY is long, random and in the environment
  • ALLOWED_HOSTS lists your domains
  • Migrations tested against a copy of production data
  • collectstatic has run
  • python manage.py check --deploy shows no warnings you cannot explain
  • Environment variables set on the server

Performance

  • Indexes on frequently filtered columns
  • N+1 queries checked on the busiest pages
  • Caching configured where it is safe
  • Database connections stay under the PostgreSQL limit

Security

  • HTTPS enforced, certificate renewal tested
  • Secure cookies and HSTS set
  • Firewall allows only SSH and web ports
  • PostgreSQL and Redis not exposed to the internet
  • Raw SQL, if any, uses query parameters

Operations

  • Database backups run on a schedule and a restore has been tested
  • Error tracking configured
  • Uptime monitoring on /health/
  • Log rotation in place for the logs/ directory

Conclusion

A standard Django deployment on Ubuntu comes down to a few parts that each do one job: Gunicorn runs the app, systemd keeps it running, Nginx handles HTTPS and static files, and PostgreSQL stores the data. Celery, Redis and Channels are additions you make only when the app needs them.

From here, the usual next steps are database backups and replication, a second app server behind an Nginx load balancer, a CDN in front of static files, and metrics and alerts for the server and the app.

Deploy a Django app from your AI agent with CloudPloy

CloudPloy lets an AI agent run a deployment through its MCP server, as an alternative to the manual steps above. In Claude Code, run claude mcp add --transport http cloudploy https://brain.cloudploy.com/mcp and sign in in the browser. There is no token to paste. Then connect AWS EC2 in your own account or a server you reach over SSH, and ask the agent to deploy your repo.

CloudPloy builds Python apps with Nixpacks, sets up SSL and deploys with zero downtime. You still need to choose your Django settings and environment variables, such as SECRET_KEY and DJANGO_SETTINGS_MODULE, and the agent can set them with set_env_vars. The MCP docs list the available tools. Free forever: 1 server, 1 app, and a hard cap of 2 vCPU / 2 GB RAM. See pricing for paid plans.

FAQ

How do I deploy a Django app to my own server?

Install Python, PostgreSQL and Nginx on an Ubuntu server, clone your code, create a virtualenv and set your environment variables. Then run migrate and collectstatic, run Gunicorn as a systemd service, put Nginx in front of it and add a free certificate with Certbot. The sections above give the commands for each step.

Do I need Nginx if I use Gunicorn?

In this setup, yes. Gunicorn is an application server and is not meant to face the internet directly. Nginx terminates TLS, serves static files and buffers slow clients so they do not block Gunicorn workers.

How do I serve Django static files in production?

Set STATIC_ROOT, run python manage.py collectstatic on every deploy, then either serve that directory with an Nginx location /static/ block or add WhiteNoise middleware so Gunicorn serves it. Django does not serve static files itself when DEBUG is False.

Can an AI agent deploy my Django app?

Yes. An AI agent such as Claude Code can deploy through an MCP server that exposes deployment tools. This walkthrough for deploying from Claude Code shows the full flow. You still review the Django settings and environment variables the agent sets.


Django is a registered trademark of the Django Software Foundation.

Updated November 19, 2026.