Zum Hauptinhalt springen
Zurück zur Kategorie

Python/Django Deploy: Produktion mit Gunicorn und Nginx

Anleitung zum Deployen von Python/Django-Anwendungen auf einem VPS. Virtualenv-Setup, Django-Produktionseinstellungen, Gunicorn WSGI-Server, Nginx Reverse Proxy, systemd-Dienst und statische Dateiverwaltung.

Lesezeit: 18 min Web Hosting / Anwendungen
pythondjangogunicornnginxdeployvpsvirtualenvwsgipostgresql

Inhaltsverzeichnis

Python/Django Deploy: Produktionsumgebung mit Gunicorn und Nginx

Django ist Pythons beliebtestes Web-Framework. Die Industriestandard-Kombination für das Produktions-Deployment ist Gunicorn (WSGI-Server) und Nginx (Reverse Proxy). Diese Anleitung führt Sie durch das Deployen einer Django-Anwendung auf einem VPS von Grund auf.

Python und Virtualenv einrichten

hljs bash
# Systemaktualisierung
sudo apt update && sudo apt upgrade -y

# Python 3 und pip installieren
sudo apt install python3 python3-pip python3-venv python3-dev -y

# Anwendungsverzeichnis erstellen
sudo mkdir -p /var/www/mydjango
sudo chown $USER:$USER /var/www/mydjango
cd /var/www/mydjango

# Virtuelle Umgebung erstellen
python3 -m venv venv

# Virtuelle Umgebung aktivieren
source venv/bin/activate

# pip aktualisieren
pip install --upgrade pip

Verwenden Sie für jedes Django-Projekt eine separate virtuelle Umgebung. Dies verhindert Abhängigkeitskonflikte und hält Projekte isoliert.

Anwendung auf den Server übertragen

hljs bash
cd /var/www
git clone https://github.com/benutzer/mydjango.git
cd mydjango
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install gunicorn

Django Produktionseinstellungen

hljs python
import os

DEBUG = False
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', '').split(',')

# Sicherheitsheader
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

# Statische Dateien
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

Datenbankeinrichtung (PostgreSQL)

hljs bash
sudo apt install postgresql postgresql-contrib -y
sudo -u postgres psql
hljs sql
CREATE DATABASE mydb;
CREATE USER dbuser WITH PASSWORD 'starkes-passwort';
ALTER ROLE dbuser SET client_encoding TO 'utf8';
ALTER ROLE dbuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE dbuser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE mydb TO dbuser;
\q
hljs bash
pip install psycopg2-binary
python manage.py migrate
python manage.py createsuperuser
python manage.py collectstatic --noinput

Gunicorn Konfiguration

hljs python
# gunicorn.conf.py
bind = 'unix:/run/gunicorn/gunicorn.sock'
workers = 3  # (2 * CPU-Kerne) + 1
worker_class = 'sync'
timeout = 30
max_requests = 1000
preload_app = True
user = 'www-data'
group = 'www-data'
errorlog = '/var/log/gunicorn/error.log'
accesslog = '/var/log/gunicorn/access.log'

Systemd-Dienstdatei

hljs ini
[Unit]
Description=Gunicorn daemon for Django
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/mydjango
ExecStart=/var/www/mydjango/venv/bin/gunicorn \
    --config /var/www/mydjango/gunicorn.conf.py \
    myproject.wsgi:application
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true
EnvironmentFile=/var/www/mydjango/.env

[Install]
WantedBy=multi-user.target
hljs bash
sudo systemctl daemon-reload
sudo systemctl start gunicorn
sudo systemctl enable gunicorn

Nginx Reverse Proxy Konfiguration

hljs nginx
server {
    listen 80;
    server_name example.com www.example.com;

    location /static/ {
        alias /var/www/mydjango/staticfiles/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    location /media/ {
        alias /var/www/mydjango/media/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn/gunicorn.sock;
        proxy_read_timeout 300;
    }

    client_max_body_size 100M;
}
hljs bash
sudo ln -s /etc/nginx/sites-available/mydjango /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

SSL-Zertifikat

hljs bash
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

Deployment-Workflow

hljs bash
cd /var/www/mydjango
source venv/bin/activate
git pull origin main
pip install -r requirements.txt
python manage.py migrate
python manage.py collectstatic --noinput
sudo systemctl restart gunicorn

Auf REXE-Servern werden für Django mindestens 1 GB RAM empfohlen. Passen Sie die Gunicorn-Worker-Anzahl basierend auf CPU-Kernen an: (2 × CPU) + 1.

Fazit

Ihre Django-Anwendung läuft jetzt in der Produktion mit Gunicorn WSGI-Server und Nginx Reverse Proxy. Dank des systemd-Dienstes startet die Anwendung automatisch beim Neustart des Servers.