Gunicorn 是有个基于 Python 的 HTTP 服务器,主要用于运行 Python 服务。

安装

pip3 install gunicorn
 
# 查看版本
gunicorn --version

运行

命令行

gunicorn -w 3 -b 127.0.0.1:8080 app:app
  • -w: 进程数量(每一核可设置 2-4个)
  • -b: 绑定 Host 和 Port(0.0.0.0:8080)
  • app: Flask 主进程名
  • app: Flask 服务名
# app.py
from flask import Flask
app = Flask(__name__)

配置文件

workers = 4 # 工作线程
bind = '0.0.0.0:80' # 80 端口
daemon = 'true' # 后台

设定完成后,使用参数 -c 使用配置文件运行: sudo gunicorn -c gunicorn.py app:app 运行

重启服务

方式一:使用 Supervisor 管理

方式二:通过 kill 命令

pstree -ap | grep gunicorn
 
# 返回
  |-gunicorn,30694 /usr/local/bin/gunicorn -c gunicorn.py app:app
  |   |-gunicorn,8530 /usr/local/bin/gunicorn -c gunicorn.py app:app
  |   |-gunicorn,8531 /usr/local/bin/gunicorn -c gunicorn.py app:app
  |   |-gunicorn,8532 /usr/local/bin/gunicorn -c gunicorn.py app:app
 
kill -HUP 30694

报错

configuration file should have a valid Python extension.

  • 把配置文件后缀改为 .py

参考