Python uWSGI 安装配置

How WSGI works, running an app behind a reverse proxy, and choosing worker counts.

Advanced
Key PointsWSGI is the sync app/proxy contract; uvicorn plays the same role for ASGI. Never expose the app server directly to the internet.

What WSGI Is

WSGI is a calling convention: the server calls app(environ, start_response) and the app returns an iterable of bytes. Flask and Django speak WSGI; FastAPI speaks ASGI.

Python
# 一个最小 WSGI 应用
def app(environ, start_response):
    body = b"hello\n"
    start_response("200 OK", [("Content-Type", "text/plain"),
                              ("Content-Length", str(len(body)))])
    return [body]

Running with Gunicorn

Bash
pip install gunicorn

# 同步 worker(Flask / Django)
gunicorn -w 4 -b 127.0.0.1:8000 app:app

# ASGI worker(FastAPI)
gunicorn -k uvicorn.workers.UvicornWorker -w 4 -b 127.0.0.1:8000 main:app

Running with uWSGI

INI
; app.ini
[uwsgi]
module = app:app
master = true
processes = 4
socket = 127.0.0.1:3031
chmod-socket = 660
vacuum = true
die-on-term = true
Bash
uwsgi --ini app.ini

Nginx in Front

NGINX
server {
    listen 80;
    server_name api.example.com;

    location / {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3031;
    }

    location /static/ {
        alias /srv/app/static/;      # 静态文件交给 nginx
    }
}
Worker typeCountNote
Sync (gunicorn)2 x CPU + 1Simple, predictable
uvicorn worker1-2 x CPUAsync concurrency inside each worker
gevent/eventletHigherMonkey-patching risk
Set --timeout and --max-requests so a leaking worker gets recycled. Without them a slow leak becomes an outage at 3am.

Friends & Partners