Python uWSGI 安装与配置指南
                           
天天向上
发布: 2025-03-18 00:10:35

原创
227 人浏览过

1. uWSGI 简介

uWSGI 是一个高性能的应用服务器,支持 WSGI、FastCGI、uWSGI 协议,常用于 Python Web 应用的部署,如 Flask 和 Django。

2. 安装 uWSGI

2.1 使用 pip 安装(推荐)

pip install uwsgi

2.2 从源码安装

git clone https://github.com/unbit/uwsgi.git
cd uwsgi
python setup.py install

3. 创建一个简单的 Flask 应用

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, uWSGI!"

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

保存为 app.py

4. 使用 uWSGI 运行 Flask 应用

uwsgi --http :5000 --wsgi-file app.py --callable app

参数说明:

  • --http :5000 监听 5000 端口
  • --wsgi-file app.py 指定 WSGI 文件
  • --callable app 指定应用实例

5. 配置 uWSGI

创建 uwsgi.ini 配置文件:

[uwsgi]
module = app:app
master = true
processes = 4
socket = uwsgi.sock
chmod-socket = 660
vacuum = true
daemonize = uwsgi.log

然后运行:

uwsgi --ini uwsgi.ini

6. 配合 Nginx 运行 uWSGI

6.1 安装 Nginx

sudo apt update
sudo apt install nginx

6.2 配置 Nginx

编辑 /etc/nginx/sites-available/default,添加:

server {
    listen 80;
    server_name example.com;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/path/to/uwsgi.sock;
    }
}

然后重启 Nginx:

sudo systemctl restart nginx

7. 常见问题与优化

7.1 启动失败问题

检查日志 uwsgi.log,常见错误包括:

  • ModuleNotFoundError: 确保 Python 虚拟环境已激活
  • Permission denied: 确保 sock 文件有正确的权限

7.2 性能优化建议

  • 增加 processesthreads 以充分利用多核 CPU
  • 启用 lazy-apps = true 以减少内存占用
  • 使用 cache2 提供内存缓存

参考链接

Nginx 官方文档: https://nginx.org/en/docs/

uWSGI 官方文档: https://uwsgi-docs.readthedocs.io

发表回复 0

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