1.安装gunicorn
pip3 install gunicorn
输出:
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting gunicorn
Downloading http://mirrors.tencentyun.com/pypi/packages/8c/da/b8dd8deb741bff556db53902d4706774c8e1e67265f69528c14c003644e6/gunicorn-19.9.0-py2.py3-none-any.whl (112kB)
100% |████████████████████████████████| 122kB 1.1MB/s
Installing collected packages: gunicorn
Successfully installed gunicorn-19.9.0
2.部署应用,测试代码:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello World"
if __name__ == "__main__":
app.run()
3.通过gunicorn启动应用
gunicorn -w 2 -b 0.0.0.0:8000 hello:app
-
# --workers = 4 表示使用 4 worker 进程运行程序,建议 worker 数量为 ( CPU 核心数 × 2 ) + 1
-
# Gunicorn 默认只允许从本地 8000 端口访问,--bind=0.0.0.0:8000 表示允许使用 8000 端口从外部访问
-
# app:app 冒号前面的 app 表示 app.py 文件,冒号后面的 app 表示 flask 程序的名称
输出:
[2019-11-02 23:45:53 +0800] [26697] [INFO] Starting gunicorn 19.9.0
[2019-11-02 23:45:53 +0800] [26697] [INFO] Listening at: http://0.0.0.0:8000 (26697)
[2019-11-02 23:45:53 +0800] [26697] [INFO] Using worker: sync
[2019-11-02 23:45:53 +0800] [26700] [INFO] Booting worker with pid: 26700
[2019-11-02 23:45:53 +0800] [26701] [INFO] Booting worker with pid: 26701
页面输出:
Hello World
在pipenv环境下运行
pipenv install gunicorn
输出
Installing gunicorn…
Adding gunicorn to Pipfile's [packages]…
✔ Installation Succeeded
Pipfile.lock (99b16b) out of date, updating to (ca72e7)…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
✔ Success!
Updated Pipfile.lock (99b16b)!
Installing dependencies from Pipfile.lock (99b16b)…
🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 1/1 — 00:00:01
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.
启动
pipenv run gunicorn -w 2 -b 0.0.0.0:8000 hello:app &
输出
[1] 20220
[root@VM_0_15_centos flask_test]# [2019-11-03 14:08:31 +0800] [20220] [INFO] Starting gunicorn 19.9.0
[2019-11-03 14:08:31 +0800] [20220] [INFO] Listening at: http://0.0.0.0:8000 (20220)
[2019-11-03 14:08:31 +0800] [20220] [INFO] Using worker: sync
[2019-11-03 14:08:31 +0800] [20233] [INFO] Booting worker with pid: 20233
[2019-11-03 14:08:31 +0800] [20234] [INFO] Booting worker with pid: 20234