Gunicorn
Gunicorn ‘Green Unicorn’ 是一个 UNIX 下的 WSGI HTTP 服务器,它是一个 移植自 Ruby 的 Unicorn 项目的 pre-fork worker 模型。它既支持 eventlet , 也支持 greenlet 。在 Gunicorn 上运行 Flask 应用非常简单:
gunicorn myproject:app
Gunicorn 提供许多命令行参数,可以使用 gunicorn -h
来获得帮助。下面 的例子使用 4 worker 进程( -w 4
)来运行 Flask 应用,绑定到 localhost 的 4000 端口( -b 127.0.0.1:4000
):
gunicorn -w 4 -b 127.0.0.1:4000 myproject:app
以上是flask中文文档的描述。基本已经告诉你怎么开启了,但是还不怎么够用。
为什么选择gunicorn?
因为简单。现在就自己玩,不需要加入Nginx。
gunicorn安装
使用virtualenv虚拟环境。我已经在tx云服务器的python工作目录建立了一个python3.7的虚拟环境:
切换到工作目录:
cd /smb/share/hdf5test
进入虚拟环境:
. venv/bin/activate
设置环境变量:
export FLASK_APP=myflask.py
以上是准备工作。
然后在虚拟环境中,安装gunicorn
pip install gunicorn
安装完成以后,看看当前gunicorn版本号:
(venv) [root@VM_0_3_centos hdf5test]# gunicorn -v
gunicorn (version 19.9.0)
前台启动gunicorn
(venv) [root@VM_0_3_centos hdf5test]# gunicorn myflask:app
[2019-08-04 17:25:29 +0800] [26280] [INFO] Starting gunicorn 19.9.0
[2019-08-04 17:25:29 +0800] [26280] [INFO] Listening at: http://127.0.0.1:8000 (26280)
[2019-08-04 17:25:29 +0800] [26280] [INFO] Using worker: sync
[2019-08-04 17:25:29 +0800] [26283] [INFO] Booting worker with pid: 26283
(venv) [root@VM_0_3_centos hdf5test]# gunicorn -w 4 -b 0.0.0.0:5000 myflask:app
[2019-08-04 17:28:16 +0800] [26607] [INFO] Starting gunicorn 19.9.0
[2019-08-04 17:28:16 +0800] [26607] [INFO] Listening at: http://0.0.0.0:5000 (26607)
[2019-08-04 17:28:16 +0800] [26607] [INFO] Using worker: sync
[2019-08-04 17:28:16 +0800] [26614] [INFO] Booting worker with pid: 26614
[2019-08-04 17:28:16 +0800] [26615] [INFO] Booting worker with pid: 26615
[2019-08-04 17:28:16 +0800] [26616] [INFO] Booting worker with pid: 26616
[2019-08-04 17:28:16 +0800] [26617] [INFO] Booting worker with pid: 26617
或者指定监听端口
gunicorn myflask:app -b -b 0.0.0.0:5000
-b ADDRESS, --bind ADDRESS
The socket to bind. [['127.0.0.1:8000']]
-w INT, --workers INT
The number of worker processes for handling requests.
[1]
执行完这一步,如果你的flask没有异常,就算正常跑起来了。
后台启动gunicorn
nohup gunicorn -w 4 -b 0.0.0.0:5000 myflask:app &
重启gunicorn
我喜欢简单粗暴,直接kill
killall -9 gunicorn
然后,在启动一次。
外网访问
http://ip:5000