🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

So stellen Sie Flask mit Gunicorn und Nginx auf Ubuntu VPS bereit: Vollständiger Leitfaden für 2026

⏱️5 min read  ·  914 words

Der integrierte Entwicklungsserver von Flask ist nicht für die Produktion geeignet – er ist Single-Threaded, verfügt über kein Prozessmanagement und stellt rohe Python-Tracebacks bereit. Eine Produktions-Flask-Bereitstellung verwendetGunicorn als WSGI-Anwendungsserver undNginx als Reverse-Proxy. Diese Anleitung behandelt die komplette Einrichtung unter Ubuntu 22.04.

Architekturübersicht

Internet → Nginx (port 80/443, SSL termination, static files)
               ↓
          Gunicorn (port 8000, multiple worker processes)
               ↓
          Flask Application (WSGI app)

Schritt 1: Server-Setup

sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-pip python3-venv nginx certbot python3-certbot-nginx

# Create application user (don't run as root)
sudo useradd -m -s /bin/bash flaskapp
sudo mkdir /var/www/myapp
sudo chown flaskapp:flaskapp /var/www/myapp

Schritt 2: Anwendung bereitstellen

sudo su - flaskapp
cd /var/www/myapp

# Clone your repo
git clone https://github.com/youruser/myapp.git .

# Create virtual environment
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install gunicorn

Ihr Flask-App-Einstiegspunkt (app.py or wsgi.py):

# wsgi.py
from myapp import create_app

app = create_app()

if __name__ == '__main__':
    app.run()

Schritt 3: Gunicorn konfigurieren

# /var/www/myapp/gunicorn.conf.py
bind              = "127.0.0.1:8000"
workers           = 4          # rule: (2 × CPU cores) + 1
worker_class      = "gthread"  # threaded worker for I/O-bound apps
threads           = 2
timeout           = 120
keepalive         = 5
max_requests      = 1000       # restart worker after N requests (prevents memory leaks)
max_requests_jitter = 50       # randomize restart to avoid thundering herd
errorlog          = "/var/log/gunicorn/error.log"
accesslog         = "/var/log/gunicorn/access.log"
loglevel          = "info"
preload_app       = True       # load app before forking workers (faster startup)
sudo mkdir /var/log/gunicorn
sudo chown flaskapp:flaskapp /var/log/gunicorn

# Test gunicorn starts correctly
cd /var/www/myapp
source venv/bin/activate
gunicorn --config gunicorn.conf.py wsgi:app

Schritt 4: systemd-Dienst

# /etc/systemd/system/myapp.service
[Unit]
Description=Gunicorn daemon for myapp
After=network.target

[Service]
User=flaskapp
Group=flaskapp
WorkingDirectory=/var/www/myapp
Environment="PATH=/var/www/myapp/venv/bin"
EnvironmentFile=/var/www/myapp/.env
ExecStart=/var/www/myapp/venv/bin/gunicorn           --config gunicorn.conf.py           wsgi:app
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp   # start on boot
sudo systemctl status myapp   # verify running

Schritt 5: Nginx-Konfiguration

# /etc/nginx/sites-available/myapp
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    # Static files served directly by Nginx (much faster than Gunicorn)
    location /static {
        alias /var/www/myapp/static;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Proxy everything else to Gunicorn
    location / {
        proxy_pass         http://127.0.0.1:8000;
        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_read_timeout 120s;
        proxy_connect_timeout 10s;

        # Security headers
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-Content-Type-Options "nosniff";
        add_header Referrer-Policy "strict-origin-when-cross-origin";
    }

    # Upload size limit
    client_max_body_size 16M;
}
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Schritt 6: SSL mit Let’s Encrypt

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

# Verify auto-renewal
sudo certbot renew --dry-run

Certbot ändert automatisch Ihre Nginx-Konfiguration, um SSL hinzuzufügen, HTTP zu HTTPS umzuleiten und fügt einen Cron-Job für die Zertifikatserneuerung hinzu.

Schritt 7: Bereitstellungsworkflow

# After code changes:
cd /var/www/myapp
git pull origin main
source venv/bin/activate
pip install -r requirements.txt  # if dependencies changed
flask db upgrade                  # if migrations exist

# Zero-downtime reload (sends SIGHUP to Gunicorn master)
sudo systemctl reload myapp

# Full restart (brief downtime)
sudo systemctl restart myapp

Umgebungsvariablen (Production)

# /var/www/myapp/.env (permissions: 600, owned by flaskapp)
FLASK_ENV=production
SECRET_KEY=your-long-random-secret-key
DATABASE_URL=postgresql://user:pass@localhost/mydb
REDIS_URL=redis://localhost:6379/0
sudo chmod 600 /var/www/myapp/.env
sudo chown flaskapp:flaskapp /var/www/myapp/.env

Monitoring and Logs

# View logs
sudo journalctl -u myapp -f          # systemd logs
sudo tail -f /var/log/gunicorn/error.log
sudo tail -f /var/log/nginx/access.log

# Check worker processes
sudo systemctl status myapp
pgrep -a gunicorn

Frequently Asked Questions

Q: How many Gunicorn workers should I use?
A: (2 × CPU cores) + 1 is the standard formula. For a 2-core VPS: 5 workers. More workers = more memory usage. Use gthread worker class with 2-4 threads for I/O-bound Flask apps.

Q: Gunicorn vs uWSGI?
A: Gunicorn for simplicity and Python ecosystem familiarity. uWSGI is faster but more complex to configure. For most Flask applications, Gunicorn performs identically and is far simpler to set up and maintain.

Q: Why not just run Flask directly on port 80?
A: Nginx handles SSL termination, static file serving (much faster), connection queueing, load balancing, security headers, and request buffering. Running Flask directly means one process per connection, no SSL optimization, and slow static file serving.

Q: How do I handle zero-downtime deploys?
A: systemctl reload myapp sends SIGHUP to Gunicorn master, which gracefully replaces workers with new ones while finishing in-flight requests. New code loads in new workers without dropping connections.

Q: Should I use Docker instead?
A: Docker is excellent for multi-service apps (with Docker Compose) and for consistency across environments. For a single Flask app on a VPS, systemd + Gunicorn + Nginx is simpler, uses less memory, and is easier to debug. Both approaches work well.

Conclusion

The Flask production stack of Gunicorn + Nginx + systemd is battle-tested, well-documented, and appropriate for applications serving thousands of requests per minute on modest VPS hardware. This setup handles: multiple worker processes for concurrency, graceful Neuladen ohne Ausfallzeiten, SSL-Terminierung, statische Dateioptimierung und automatischer Neustart des Prozesses bei Fehlern – das ist alles, was Sie brauchen, um eine Produktions-Flask-Anwendung zuverlässig bereitzustellen.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা