Django:Nginx und Gunicorn
Hinweis: Diese Inhalte wurden mit Unterstützung von Künstlicher Intelligenz erstellt und redaktionell überprüft (Transparenzhinweis gemäß Art. 50 EU AI Act).
Nginx und Gunicorn
Nginx ist ein Webserver, der häufig als Reverse-Proxy-Server eingesetzt wird. Gunicorn ist ein WSGI-HTTP-Server für Python-Anwendungen. In diesem Artikel wird erläutert, wie Sie Nginx und Gunicorn zusammen verwenden können, um eine Django-Anwendung zu hosten.
Systemctl-Service für Gunicorn erstellen
Erstellen Sie eine Systemctl-Service-Datei für Gunicorn, um den Gunicorn-Server als Dienst auf Ihrem Server zu starten und zu stoppen. Erstellen Sie eine Datei mit dem Namen `gunicorn.service` im Verzeichnis `/etc/systemd/system/` und fügen Sie den folgenden Inhalt hinzu:
sudo nano /etc/systemd/system/gunicorn.service
Folgene Inhalt hinzufügen:
[Unit] Description=Gunicorn daemon for Django project After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/home/thorsten/portal ExecStart=/home/thorsten/portal/.venv/bin/gunicorn --bind 0.0.0.0:8000 myapp:app [Install] WantedBy=multi-user.target
Starten Sie den Gunicorn-Service
sudo systemctl daemon-reload # Reload systemctl to read the new service file sudo systemctl start my_gunicorn_service # Start the Gunicorn service sudo systemctl enable my_gunicorn_service # Enable the Gunicorn service to start on boot
Nginx-Konfiguration für Gunicorn
Erstellen Sie eine Nginx-Konfigurationsdatei für Ihre Django-Anwendung. Erstellen Sie eine Datei mit dem Namen `my_django_app` im Verzeichnis `/etc/nginx/sites-available/` und fügen Sie den folgenden Inhalt hinzu:
sudo nano /etc/nginx/sites-available/my_django_app
Folgene Inhalt hinzufügen:
server {
listen 80;
server_name your_domain.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /path/to/your/django/project;
}
location / {
include proxy_params;
proxy_pass http://
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
}
}
Hinweis: Diese Inhalte wurden mit Unterstützung von Künstlicher Intelligenz erstellt und redaktionell überprüft (Transparenzhinweis gemäß Art. 50 EU AI Act).