一、简介
Gunicorn被广泛应用的高性能的Python HTTP Server。用来解析HTTP请求的网关服务。
它介于web 服务器和应用之间。例如: nginx --> gunicorn --> Flask
特点:
1.能和大多数的Python Web框架兼容
2.简单易上手
3.轻量级的资源消耗
4.目前,gunicorn只能运行在Linux环境中,不支持windows平台
二、安装
pip3 install gunicorn
查看安装信息
[root@node-2 ~]# pip3 show gunicorn
Name: gunicorn
Version: 21.2.0
Summary: WSGI HTTP Server for UNIX
Home-page: https://gunicorn.org
Author: Benoit Chesneau
Author-email: benoitc@gunicorn.org
License: MIT
Location: /usr/local/lib/python3.6/site-packages
Requires: packaging, importlib-metadata
1.使用python启动flask
[root@node-2 python]# python3 main.py
#查看进程
[root@node-2 ~]# ps aux |grep main
root 1546 0.1 1.2 237028 25100 pts/0 S+ 00:40 0:00 python3 main.py
root 1550 0.6 1.2 329892 25668 pts/0 Sl+ 00:40 0:00 /usr/bin/python3 /root/pangbb/main.py
2.启动前
2.1 先查看系统cpu数量
[root@node-2 ~]# cat /proc/cpuinfo |grep processor
processor : 0
processor : 1
processor : 2
processor : 3
processor : 4
processor : 5
2.2 启动参数
参数 | 短参数 | 说明 |
---|---|---|
–bind | -b | 绑定服务的IP和端口号 |
–workers 数字 | -w | 工作线程数量---- |
–daemon | -D | 后台运行 |
–pidfile | pid存储文件路径 | |
–error-logfile FILE | –log-file | 错误日志文件 |
–access-logfile FILE | 访问日志文件 |
2.3 样例代码
[root@node-2 python]# cat main.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "index"
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0')
三、启动
1.命令行启动
这里暂时没有使用-D ,为了看到启动过程。
解释:
gunicorn -w 4 -b 0.0.0.0:6666 main:app
main: 是启动文件名称
app: 是Flask(__name__)的实例化名称,也就是 app = Flask(__name__) 中的app
[root@node-2 python]# gunicorn -w 4 -b 0.0.0.0:6666 main:app
[2024-01-08 01:53:09 -0500] [1644] [INFO] Starting gunicorn 21.2.0
[2024-01-08 01:53:09 -0500] [1644] [INFO] Listening at: http://0.0.0.0:6666 (1644) #此进程加上下边4个进程 正好5个进程
[2024-01-08 01:53:09 -0500] [1644] [INFO] Using worker: sync
[2024-01-08 01:53:09 -0500] [1647] [INFO] Booting worker with pid: 1647
[2024-01-08 01:53:09 -0500] [1648] [INFO] Booting worker with pid: 1648
[2024-01-08 01:53:09 -0500] [1650] [INFO] Booting worker with pid: 1650
[2024-01-08 01:53:09 -0500] [1651] [INFO] Booting worker with pid: 1651
启动后的进程数量
[root@node-2 python]# ps aux |grep main
1644 0.2 0.8 216700 18068 pts/0 S+ 01:53 0:00 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:6666 main:app
1647 0.3 1.2 240776 24468 pts/0 S+ 01:53 0:00 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:6666 main:app
1648 0.3 1.2 240672 24448 pts/0 S+ 01:53 0:00 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:6666 main:app
1650 0.3 1.2 240672 24452 pts/0 S+ 01:53 0:00 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:6666 main:app
1651 0.3 1.2 240672 24500 pts/0 S+ 01:53 0:00 /usr/bin/python3 /usr/local/bin/gunicorn -w 4 -b 0.0.0.0:6666 main:app
2.命令行后台启动
短参数
gunicorn -D -w 4 -b 0.0.0.0:6666 main:app
长参数启动
gunicorn -D --workers=4 --bind=0.0.0.0:6666 main:app
记录日志
gunicorn -D --workers=4 --bind=0.0.0.0:6666 --access-logfile=./access.log --error-logfile=./error.log main:app