独角兽

Gunicorn 是一个纯粹的PythonWSGI服务器,具有简单的配置和用于性能调优的多个Worker实现。

  • 它往往很容易与托管平台集成。

  • 它不支持Windows(但可以在WSL上运行)。

  • 它很容易安装,因为它不需要额外的依赖项或编译。

  • 它具有内置的使用GEvent或Eventlet的异步工作者支持。

本页概述了运行Gunicorn的基本知识。一定要阅读它的 documentation 和使用 gunicorn --help 以了解哪些功能可用。

正在安装

Gunicorn很容易安装,因为它不需要外部依赖或编译。它只能在WSL下运行在Windows上。

创建一个Virtualenv,安装应用程序,然后安装 gunicorn

$ cd hello-app
$ python -m venv venv
$ . venv/bin/activate
$ pip install .  # install your application
$ pip install gunicorn

正在运行

Gunicorn的唯一必需参数告诉它如何加载应用程序。其语法为 {module_import}:{app_variable}module_import 是包含应用程序的模块的带点的导入名称。 app_variable 是应用程序的变量。如果您使用的是应用程序工厂模式,它也可以是函数调用(带有任何参数)。

# equivalent to 'from hello import app'
$ gunicorn -w 4 'hello:app'

# equivalent to 'from hello import create_app; create_app()'
$ gunicorn -w 4 'hello:create_app()'

Starting gunicorn 20.1.0
Listening at: http://127.0.0.1:8000 (x)
Using worker: sync
Booting worker with pid: x
Booting worker with pid: x
Booting worker with pid: x
Booting worker with pid: x

这个 -w 选项指定要运行的进程数;起始值可以是 CPU * 2 。默认值仅为1个Worker,这可能不是您想要的默认Worker类型。

默认情况下,不会显示每个请求的日志,仅显示工作人员信息和错误。要在标准输出上显示访问日志,请使用 --access-logfile=- 选择。

对外约束

Gunicorn不应以超级用户身份运行,因为这会导致应用程序代码以超级用户身份运行,这是不安全的。但是,这意味着无法绑定到端口80或443。相反,像这样的反向代理 恩吉克斯ApacheHTTPD 应该在Gunicorn前面使用。

可以使用绑定到非特权端口上的所有外部IP -b 0.0.0.0 选择。在使用反向代理设置时不要执行此操作,否则可能会绕过代理。

$ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()'
Listening at: http://0.0.0.0:8000 (x)

0.0.0.0 不是有效的导航地址,则需要在浏览器中使用特定的IP地址。

与GEvent或Eventlet同步

默认同步工作器适用于许多用例。如果您需要异步支持,Gunicorn提供了使用以下两种方法之一的工作人员 geventeventlet 。这与Python的不同 async/await 或ASGI服务器规范。您必须在自己的代码中实际使用gEvent/Eventlet,才能看到使用Worker的任何好处。

当使用GEVENT或Eventlet时,需要greenlet>=1.0,否则上下文本地变量,如 request 将不会像预期的那样工作。使用PyPy时,需要使用>=7.3.7的PyPy。

要使用GEvent,请执行以下操作:

$ gunicorn -k gevent 'hello:create_app()'
Starting gunicorn 20.1.0
Listening at: http://127.0.0.1:8000 (x)
Using worker: gevent
Booting worker with pid: x

要使用Eventlet,请执行以下操作:

$ gunicorn -k eventlet 'hello:create_app()'
Starting gunicorn 20.1.0
Listening at: http://127.0.0.1:8000 (x)
Using worker: eventlet
Booting worker with pid: x