01 Gunicorn 入门
介绍
Gunicorn 就是 Green Unicorn 的缩写,是Unix系统下Python的一个WSGI Http服务器。 它的优点就是比较简单,很容易用在其他web框架上,比如flask 、Django等等。
安装和启动
pip install gunicorn
使用上面的命令安装好gunicorn,然后写一个简单的python脚本来启动服务
# myapp.py
def app(environ, start_response):
data = b"Hello, World!\n"
start_response("200 OK",[("Content-Type","text/plain"),("Content-Length",str(len(data)))])
return iter([data])
# 启动:
gunicorn -w 4 myapp:app
运行结果如下:
[2021-04-11 20:59:22 +0800] [32842] [INFO] Starting gunicorn 20.1.0
[2021-04-11 20:59:22 +0800] [32842] [INFO] Listening at: http://127.0.0.1:8000 (32842)
[2021-04-11 20:59:22 +0800] [32842] [INFO] Using worker: sync
[2021-04-11 20:59:22 +0800] [32844] [INFO] Booting worker with pid: 32844
[2021-04-11 20:59:22 +0800] [32845] [INFO] Booting worker with pid: 32845
[2021-04-11 20:59:22 +0800] [32846] [INFO] Booting worker with pid: 32846
[2021-04-11 20:59:22 +0800] [32847] [INFO] Booting worker with pid: 32847
部署
Gunicorn是一种WSGI HTTP服务器。使用Gunicorn的时候最好放在HTTP代理服务器后面,官方推荐使用Nginx。 简单的Nginx配置如下:
server {
listen 80;
server_name example.org;
access_log /var/log/nginx/example.log;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
在这里,Nginx被设置为在本地主机端口8000上运行的Gunicorn服务器的反向代理服务器。