如何用 uWSGI 托管 DjangoLink to this heading

uWSGI 是一个快速的,自我驱动的,对开发者和系统管理员友好的应用容器服务器,完全由 C 编写。

前置条件:uWSGILink to this heading

uWSGI 百科介绍了几种 安装流程。Pip (Python 包管理器)能让你仅用一行代码就安装任意版本的 uWSGI。例子:

Shell
# Install current stable version.
$ pip install uwsgi

# Or install LTS (long term support).
$ pip install https://projects.unbit.it/downloads/uwsgi-lts.tar.gz

uWSGI 模块Link to this heading

uWSGI 以客户端-服务端模式运行。Web 服务器(例如 nginx,Apache)与一个 django-uwsgi "worker" 进程交互,提供动态内容。

配置并启动用于 Django 的 uWSGI 服务器Link to this heading

uWSGI 支持多种配置进程的方式。参考 uWSGI 的 配置文档

以下是个示例命令,用于启动一个 uWSGI 服务器:

Shell
uwsgi --chdir=/path/to/your/project \
    --module=mysite.wsgi:application \
    --env DJANGO_SETTINGS_MODULE=mysite.settings \
    --master --pidfile=/tmp/project-master.pid \
    --socket=127.0.0.1:49152 \      # can also be a file
    --processes=5 \                 # number of worker processes
    --uid=1000 --gid=2000 \         # if root, uwsgi can drop privileges
    --harakiri=20 \                 # respawn processes taking more than 20 seconds
    --max-requests=5000 \           # respawn processes after serving 5000 requests
    --vacuum \                      # clear environment on exit
    --home=/path/to/virtual/env \   # optional path to a virtualenv
    --daemonize=/var/log/uwsgi/yourproject.log      # background the process

假设你有个叫做 mysite 的顶级项目包,期中包含一个模板 mysite/wsgi.py,模块包含一个 WSGI application 对象。如果你使用的是较新的 Django,这就是你运行 django-admin startproject mysite (使用你的项目名替换 mysite)后得到的目录结构。若该文件不存在,你需要创建它。参考文档 如何使用 WSGI 进行部署 看看你需要配置的默认内容,以及你还能添加什么。

Django 指定的参数如下:

  • chdir:需要包含于 Python 的导入路径的目录的路径——例如,包含 mysite 包的目录。

  • module:要使用的 WSGI 模块——可能是 startproject 创建的 mysite.wsgi 的模块。

  • env:至少要包括 DJANGO_SETTINGS_MODULE

  • home: 可选的路径,指向你工程的 virtualenv。

示例 ini 配置文件:

Shell
[uwsgi]
chdir=/path/to/your/project
module=mysite.wsgi:application
master=True
pidfile=/tmp/project-master.pid
vacuum=True
max-requests=5000
daemonize=/var/log/uwsgi/yourproject.log

示例 ini 配置文件语法:

Shell
uwsgi --ini uwsgi.ini

参考 uWSGI 文档 管理 uWSGI 进程 获取更多关于开启,关闭和重载 uWSGI workers 的信息。