大多数 Django 项目建议优先选 Gunicorn,配置简单、维护成本低;只有在需要极限性能调优或特殊协议支持时才考虑 uWSGI。
先说结论:Gunicorn 适合绝大多数 Django 生产部署场景,uWSGI 仅在特定需求下才有优势。
- 适合:中小流量项目、容器化部署、希望配置简单快速上线
- 重点看:社区维护状态、配置复杂度、与 Nginx 的对接方式
- 别忽略:中文教程偏向 uWSGI 主要是历史原因,不代表当前最佳实践
核心区别与选型建议
两者都是 WSGI 服务器,核心任务是把 HTTP 请求转给 Django 处理。区别在于实现方式和功能定位。
Gunicorn 专注 WSGI 应用,用 Python 编写,配置参数少,默认设置就能应付大多数场景。uWSGI 用 C 语言实现,支持更多协议(uWSGI 协议、HTTP、FastCGI 等),功能更丰富但配置项也多。
性能方面,公开测试显示两者在正常流量范围内差距不明显。对于典型的 IO 密集型 Django 应用,Gunicorn 的稳定性与维护性优势远大于微弱的性能差异。
生产环境部署实操
1. 安装依赖
# Gunicorn
pip install gunicorn# uWSGI
pip install uwsgi2. 启动命令测试
先通过命令行验证能否启动,注意参数不要带反引号。
# Gunicorn 启动命令(推荐)
gunicorn `--workers` 4 `--bind` 127.0.0.1:8000 myproject.wsgi:application# uWSGI 启动命令
uwsgi `--socket` 127.0.0.1:8000 `--workers` 4 `--module` myproject.wsgi:application3. Systemd 守护进程配置(生产必备)
生产环境不建议直接用命令行后台运行,应使用 systemd 管理。
[Unit]
Description=myproject gunicorn daemon
After=network.target[Service]
User=www-data
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/venv/bin/gunicorn `--workers` 4 `--bind` unix:/run/gunicorn.sock myproject.wsgi:application[Install]
WantedBy=multi-user.target保存为/etc/systemd/system/myproject.service,然后执行systemctl start myproject。
4. Nginx 配置对接
Gunicorn 配置示例(HTTP 协议):
server {listen 80;server_name example.com;location / {proxy_pass http://127.0.0.1:8000;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}
}uWSGI 配置示例(Socket 协议):
server {listen 80;server_name example.com;location / {include uwsgi_params;uwsgi_pass unix:/path/to/socket.sock;}
}性能调优与 Worker 设置
Worker 数量设置需区分场景,盲目套用公式可能导致性能不佳。
- IO 密集型(大多数 Django 项目):建议初始设为 CPU 核数 × 2 到 × 4。观察 CPU 使用率,若长期低于 50% 且响应慢,可适当增加。
- CPU 密集型(大量计算):建议设为 CPU 核数 × 2 + 1。
- 监控调整:使用
htop观察进程状态,若大量进程处于 Sleep 状态且请求排队,可增加 Worker;若上下文切换过高,应减少。
验证与排查
1. 检查进程与端口
ps -ef | grep gunicorn
ss -tlnp | grep 80002. 查看日志
重点查看 Nginx 错误日志/var/log/nginx/error.log和应用标准输出。
3. 常见报错解决
- 502 Bad Gateway:通常是后端服务未启动或 Socket 文件权限不对。检查 systemd 状态
systemctl status myproject,确保 Nginx 用户有权读取 Socket 文件。 - unable to load app:uWSGI 的
`--module`路径错误。确保指向正确的wsgi:application,且项目在 Python 路径中。 - 静态文件 404:WSGI 服务器不建议处理静态文件。确保 Nginx 配置了
location /static/指向collectstatic后的目录。
参考来源
- Gunicorn Official Documentation
- uWSGI Official Documentation
- Django Deployment Options (Official)
- Community benchmarks on Python Web Servers (General Consensus)
原文链接:https://www.zjcp.cc/ask/10885.html
