Python uWSGI 安装配置
How WSGI works, running an app behind a reverse proxy, and choosing worker counts.
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:appRunning 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 = trueBash
uwsgi --ini app.iniNginx 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 type | Count | Note |
|---|---|---|
| Sync (gunicorn) | 2 x CPU + 1 | Simple, predictable |
| uvicorn worker | 1-2 x CPU | Async concurrency inside each worker |
| gevent/eventlet | Higher | Monkey-patching risk |
Set
--timeout and --max-requests so a leaking worker gets recycled. Without them a slow leak becomes an outage at 3am.WSGI 是什么
WSGI 是一套调用约定:服务器调用 app(environ, start_response),应用返回字节可迭代对象。Flask、Django 说 WSGI;FastAPI 说 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]用 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用 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 = trueBash
uwsgi --ini app.ini前面挂 Nginx
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 类型 | 数量 | 说明 |
|---|---|---|
| 同步(gunicorn) | 2 × CPU + 1 | 简单可预测 |
| uvicorn worker | 1~2 × CPU | 每个 worker 内部异步并发 |
| gevent/eventlet | 可更高 | 有 monkey patch 风险 |
设置
--timeout 与 --max-requests,让有内存泄漏的 worker 被回收。不设的话,缓慢泄漏会在凌晨变成故障。