Django is the most popular Python web framework for production applications — from SaaS dashboards to REST APIs to content platforms. Deploying it on a Hong Kong VPS with CN2 GIA routing gives Asia-Pacific users sub-50ms response times while you maintain full control over your Python environment, dependencies, and infrastructure. This guide covers a complete production stack: Gunicorn WSGI server, Nginx reverse proxy, PostgreSQL, Redis, and Celery async workers.
Stack Overview
Internet → Nginx (TLS, static files, rate limit)
↓
Gunicorn (Python WSGI, 4 workers)
↓
Django Application
↓
PostgreSQL ← → Redis ← → Celery Workers
Step 1: System Preparation
apt update && apt upgrade -y
apt install -y python3 python3-pip python3-venv python3-dev \
nginx postgresql postgresql-contrib redis-server \
libpq-dev gcc certbot python3-certbot-nginx ufw
# Application user (never run Django as root)
useradd -m -s /bin/bash django
mkdir -p /var/www/myproject
chown django:django /var/www/myproject
ufw allow 22/tcp && ufw allow 80/tcp && ufw allow 443/tcp && ufw enable
Step 2: Set Up PostgreSQL
sudo -u postgres psql << 'SQL'
CREATE DATABASE myproject_prod;
CREATE USER myproject_user WITH PASSWORD 'StrongDBPassword!';
ALTER ROLE myproject_user SET client_encoding TO 'utf8';
ALTER ROLE myproject_user SET default_transaction_isolation TO 'read committed';
ALTER ROLE myproject_user SET timezone TO 'Asia/Hong_Kong';
GRANT ALL PRIVILEGES ON DATABASE myproject_prod TO myproject_user;
SQL
Step 3: Deploy Django Application
su - django
cd /var/www/myproject
# Clone your project
git clone https://github.com/your-org/myproject.git .
# Create virtual environment
python3 -m venv venv
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
pip install gunicorn psycopg2-binary redis django-redis celery
Production settings.py
<code">cat > /var/www/myproject/myproject/settings_production.py << 'EOF'
from .settings import *
import os
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'myproject_prod',
'USER': 'myproject_user',
'PASSWORD': os.environ['DB_PASSWORD'],
'HOST': 'localhost',
'PORT': '5432',
'CONN_MAX_AGE': 60,
}
}
# Redis cache
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': f"redis://:{os.environ['REDIS_PASSWORD']}@127.0.0.1:6379/0",
'OPTIONS': {'CLIENT_CLASS': 'django_redis.client.DefaultClient'}
}
}
# Session via Redis
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
# Static files
STATIC_ROOT = '/var/www/myproject/staticfiles'
MEDIA_ROOT = '/var/www/myproject/media'
# Celery
CELERY_BROKER_URL = f"redis://:{os.environ['REDIS_PASSWORD']}@127.0.0.1:6379/1"
CELERY_RESULT_BACKEND = f"redis://:{os.environ['REDIS_PASSWORD']}@127.0.0.1:6379/2"
# Security
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
EOF
Environment File
<code">cat > /var/www/myproject/.env << 'EOF' DJANGO_SETTINGS_MODULE=myproject.settings_production DJANGO_SECRET_KEY=GENERATE_50_CHAR_SECRET_HERE DB_PASSWORD=StrongDBPassword! REDIS_PASSWORD=StrongRedisPassword! EOF chmod 600 /var/www/myproject/.env
Run Initial Setup
<code">source venv/bin/activate export $(cat .env | xargs) python manage.py migrate python manage.py collectstatic --noinput python manage.py createsuperuser
Step 4: Configure Gunicorn with Systemd
<code">exit # Back to root
cat > /etc/systemd/system/gunicorn.service << 'EOF'
[Unit]
Description=Gunicorn daemon for Django myproject
After=network.target
[Service]
User=django
Group=www-data
WorkingDirectory=/var/www/myproject
EnvironmentFile=/var/www/myproject/.env
ExecStart=/var/www/myproject/venv/bin/gunicorn \
--workers 4 \
--worker-class gthread \
--threads 2 \
--worker-connections 1000 \
--bind unix:/run/gunicorn/myproject.sock \
--timeout 60 \
--keep-alive 5 \
--max-requests 1000 \
--max-requests-jitter 100 \
--log-level info \
--error-logfile /var/log/gunicorn/error.log \
--access-logfile /var/log/gunicorn/access.log \
myproject.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
RuntimeDirectory=gunicorn
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
mkdir -p /run/gunicorn /var/log/gunicorn
chown django:www-data /run/gunicorn /var/log/gunicorn
systemctl enable --now gunicorn
Step 5: Configure Nginx
<code">cat > /etc/nginx/sites-available/myproject << 'EOF'
upstream django_backend {
server unix:/run/gunicorn/myproject.sock fail_timeout=0;
}
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
client_max_body_size 50m;
# Serve Django static files directly (bypass Gunicorn)
location /static/ {
alias /var/www/myproject/staticfiles/;
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
location /media/ {
alias /var/www/myproject/media/;
expires 30d;
add_header Cache-Control "public";
}
# All other requests to Gunicorn
location / {
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;
proxy_redirect off;
proxy_pass http://django_backend;
proxy_read_timeout 60s;
proxy_connect_timeout 10s;
}
}
EOF
ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/
certbot --nginx -d yourdomain.com -d www.yourdomain.com
nginx -t && systemctl reload nginx
Step 6: Celery Workers for Async Tasks
<code">cat > /etc/systemd/system/celery.service << 'EOF' [Unit] Description=Celery worker for myproject After=network.target [Service] User=django Group=django WorkingDirectory=/var/www/myproject EnvironmentFile=/var/www/myproject/.env ExecStart=/var/www/myproject/venv/bin/celery \ -A myproject worker \ --loglevel=info \ --concurrency=4 \ --logfile=/var/log/celery/worker.log \ --max-tasks-per-child=500 Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target EOF # Celery Beat for scheduled tasks cat > /etc/systemd/system/celery-beat.service << 'EOF'
[Unit]
Description=Celery Beat scheduler for myproject
After=network.target
[Service]
User=django
Group=django
WorkingDirectory=/var/www/myproject
EnvironmentFile=/var/www/myproject/.env
ExecStart=/var/www/myproject/venv/bin/celery \
-A myproject beat \
--loglevel=info \
--logfile=/var/log/celery/beat.log \
--schedule=/var/www/myproject/celerybeat-schedule
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
mkdir -p /var/log/celery
chown django:django /var/log/celery
systemctl enable --now celery celery-beat
Step 7: Gunicorn Worker Count
The standard formula for Gunicorn workers on a CPU-bound application:
<code"># Workers = (2 × vCPUs) + 1 # For a 4 vCPU VPS: 2×4+1 = 9 workers # But with gthread worker class, fewer workers + more threads is often better: # 4 workers × 2 threads = 8 concurrent requests without GIL contention # For I/O-bound apps (many DB/API calls): # Use gevent or eventlet worker class for higher concurrency: pip install gevent # Then: --worker-class gevent --worker-connections 1000
Step 8: Deployment Script
<code">cat > /home/django/deploy.sh << 'EOF' #!/bin/bash set -e cd /var/www/myproject source venv/bin/activate export $(cat .env | xargs) echo "Pulling latest code..." git pull origin main echo "Installing dependencies..." pip install -r requirements.txt -q echo "Running migrations..." python manage.py migrate --noinput echo "Collecting static files..." python manage.py collectstatic --noinput -v 0 echo "Restarting Gunicorn..." sudo systemctl restart gunicorn echo "Restarting Celery..." sudo systemctl restart celery celery-beat echo "Deploy complete!" EOF chmod +x /home/django/deploy.sh
Performance: Django on Hong Kong VPS
| Metric | 4 vCPU HK VPS | Notes |
|---|---|---|
| Cached page TTFB (Shanghai) | 30–60ms | Redis + CN2 GIA |
| DB-driven page TTFB (Shanghai) | 60–150ms | Indexed queries |
| API endpoint (GET, cached) | 20–40ms | Redis cache hit |
| Concurrent requests (gthread) | 200–500 | 4 workers × 2 threads + keepalive |
| Celery jobs/minute | 500–2,000 | Depends on task I/O |
Conclusion
A production Django deployment on a Hong Kong VPS — with Gunicorn, Nginx serving static files directly, PostgreSQL with connection pooling via psycopg2, Redis caching, and Celery for async tasks — handles serious production workloads at a fraction of managed cloud costs. CN2 GIA routing delivers sub-60ms TTFB to mainland Chinese users, making Hong Kong the optimal VPS location for Python/Django applications targeting Asia-Pacific audiences.
Deploy your Django app: Browse Server.HK Hong Kong VPS plans — a 4 GB plan with 4 vCPU handles Gunicorn, PostgreSQL, Redis, and Celery workers comfortably.