一、简介
Gunicorn 意即 Green Unicorn,绿色独角兽。它是一个被广泛使用的高性能的 Python WSGI UNIX HTTP服务器,移植自Ruby的独角兽(Unicorn )项目。
它具有如下特性:
-
原生支持 WSGI、Django 和 Paster
-
自动工作进程管理
-
简单的 Python 配置
-
多个 worker 配置
-
多种可扩展性服务器挂钩
-
兼容 Python 3.x >= 3.5
二、安装
$ pip install gunicorn
或者从源码安装:
$ pip install git+https://github.com/benoitc/gunicorn.git
如果你需要使用异步 workers,你还需要安装:
$ pip install greenlet # Required for both
$ pip install eventlet # For eventlet workers
$ pip install gunicorn[eventlet] # Or, using extra
$ pip install gevent # For gevent workers
$ pip install gunicorn[gevent] # Or, using extra
三、使用
假如你有以下应用:
def app(environ, start_response):
"""Simplest possible application object"""
data = b'Hello, World!\n'
status = '200 OK'
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(data)))
]
start_response(status, response_headers)
return iter([data])
命令行启动:
$ gunicorn --workers=2 test:app
也可以使用工厂模式:
def create_app():
app = FrameworkApp()
...
return app
命令行启动:
$ gunicorn --workers=2 'test:create_app()'
四、配置
Gunicorn从5个地方依次读取配置:
- 环境变量
- 框架配置
- gunicorn.conf.py 配置文件
- 环境变量中的 GUNICORN_CMD_ARGS
- 命令行
常见配置项:
-
--config
配置文件 -
--reload
代码更改时重新启动 -
--access-logfile
要写入的访问日志文件 -
--error-logfile
要写入的错误日志文件 -
--log-level
错误输出级别 -
--certfile
SSL证书文件 -
--bind
绑定socket -
--workers
处理请求的工作进程数 -
--threads
用于处理请求的工作线程数
五、服务器钩子
on_starting
在主进程初始化之前调用on_reload
重新加载期间调用when_ready
在服务器启动后立即调用pre_fork
在fork之前调用post_fork
在fork之后调用post_worker_init
在work初始化之后调用worker_int
在worker 退出 SIGINT 或 SIGQUIT 后立即调用worker_abort
在worker 收到SIGABRT 信号时调用pre_exec
新的主进程之前调用pre_request
处理请求之前调用post_request
处理请求后调用child_exit
在主进程中退出工作程序后立即调用worker_exit
worker退出后调用nworkers_changed
在_num_workers_更改后_立即_调用on_exit
在退出 Gunicorn 之前调用
六、部署
官方强烈建议在代理服务器后面使用 Gunicorn。
Nginx:
尽管有许多可用的 HTTP 代理,但官方建议您使用 Nginx。
Nginx配置文件示例:
worker_processes 1;
user nobody nogroup;
# 'user nobody nobody;' for systems with 'nobody' as a group instead
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024; # increase if you have lots of clients
accept_mutex off; # set to 'on' if nginx worker_processes > 1
# 'use epoll;' to enable for Linux 2.6+
# 'use kqueue;' to enable for FreeBSD, OSX
}
http {
include mime.types;
# fallback in case we can't determine a type
default_type application/octet-stream;
access_log /var/log/nginx/access.log combined;
sendfile on;
upstream app_server {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response
# for UNIX domain socket setups
server unix:/tmp/gunicorn.sock fail_timeout=0;
# for a TCP configuration
# server 192.168.0.7:8000 fail_timeout=0;
}
server {
# if no Host match, close the connection to prevent host spoofing
listen 80 default_server;
return 444;
}
server {
# use 'listen 80 deferred;' for Linux
# use 'listen 80 accept_filter=httpready;' for FreeBSD
listen 80;
client_max_body_size 4G;
# set the correct host(s) for your site
server_name example.com www.example.com;
keepalive_timeout 5;
# path for static files
root /path/to/app/current/public;
location / {
# checks for static file, if not found proxy to app
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
proxy_pass http://app_server;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /path/to/app/current/public;
}
}
}
如果您希望能够处理流请求/响应或其他功能,如 Comet、长轮询或 Web sockets,您需要关闭代理缓冲。**执行此操作时,**您必须使用异步worker 。
要关闭缓冲,您只需要设置:proxy_buffering
off;
...
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_buffering off;
proxy_pass http://app_server;
}
...
建议将协议信息传递给 Gunicorn。许多 Web 框架使用此信息来生成 URL。如果没有此信息,应用程序可能会错误地在“https”响应中生成“http”URL,从而导致混合内容警告或应用程序损坏,设置proxy_set_header
即可:
...
proxy_set_header X-Forwarded-Proto $scheme;
...
如果您在不同的主机上运行 Nginx,您需要告诉 Gunicorn 信任X-Forwarded-*
。默认情况下,Gunicorn 只会信任 localhost 的这些标头。这是为了防止客户端恶意伪造这些标头:
gunicorn -w 3 --forwarded-allow-ips="10.170.3.217,10.170.3.220" test:app