目录
1、写一个app,FlaskDemo 命名为 test.py
3.3: 优化启动方式:通过调用配置文件gunicorn.conf启动 (推荐)
1、如果运行出现以下警告,尝试将文件gunicorn.conf 更改为 gunicorn.py在运行
2、gunicorn报错gunicorn.errors.HaltServer:
1、写一个app,FlaskDemo 命名为 test.py
# coding=utf-8 from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "test" if __name__ == '__main__': app.debug = True app.run(host="0.0.0.0", port=5000)
2、服务器配置,安装gunicorn
# 必须安装的包
pip install gunicornsudo apt install gunicorn
3、运行
3.1:直接运行(测试时使用)
python test.py runserver
3.2:gunicorn运行
#直接运行,默认启动的127.0.0.1::8000
gunicorn 运行文件名称:Flask程序实例名#指定端口
gunicorn -w 4 -b HOST:端口 运行文件名称:Flask程序实例名#-w 表示进程(worker)。
#-b 表示绑定ip地址和端口号(bind)
# test 运行的文件名称 对应 test.py
# app Flask程序实例名 对应 app = Flask(__name__)如:
#直接运行
gunicorn -w 4 -b 0.0.0.0:5000 test:app#后台运行
gunicorn -w 4 -b 127.0.0.1:5000 test:app --daemon
3.3: 优化启动方式:通过调用配置文件gunicorn.conf启动 (推荐)
# 并行工作线程数
workers = multiprocessing.cpu_count() * 2 + 1 # 进程数# 监听内网端口5000【按需要更改】
bind = "0.0.0.0:25001"# 使用gevent模式,还可以使用sync 模式,默认的是sync模式
worker_class = "gevent" worker_connections = 100# 设置守护进程【关闭连接时,程序仍在运行】
daemon = True # 设置超时时间60s,默认为30s。按自己的需求进行设置 timeout = 60 # 设置访问日志和错误信息日志路径 backlog = 2048 pidfile = "logs/gunicorn.pid" loglevel = "info" accesslog = "logs/gunicorn_access.log" errorlog = "logs/gunicorn_debug.log"
gunicorn配置参数详解:
运行程序
# gunicorn 运行模块名:应用名 -c 配置文件
gunicorn service:app -c gunicorn.conf
3.4:如果你想尝试使用其他py版本运行
查看gunicorn位置
which gunicorn
2.打开文件并编辑第一行指定版本
#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
import re
import sysfrom gunicorn.app.wsgiapp import run
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(run())
3.运行
gunicorn server:app -c gunicorn.conf
报错处理:
1、如果运行出现以下警告,尝试将文件gunicorn.conf 更改为 gunicorn.py在运行
!!!
!!! WARNING: configuration file should have a valid Python extension.
!!!
2、gunicorn报错gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
[root@zq ~]# gunicorn --reload --bind=127.0.0.1:5013 --workers=4 --timeout 180 logquery_service:app
[2020-06-18 13:46:38 +0000] [2068] [INFO] Starting gunicorn 19.7.1
[2020-06-18 13:46:38 +0000] [2068] [INFO] Listening at: http://127.0.0.1:5013 (2068)
[2020-06-18 13:46:38 +0000] [2068] [INFO] Using worker: sync
[2020-06-18 13:46:38 +0000] [2073] [INFO] Booting worker with pid: 2073.....
File "/opt/poc/lib/python2.7/site-packages/gunicorn/arbiter.py", line 244, in handle_chld
self.reap_workers()
File "/opt/poc/lib/python2.7/site-packages/gunicorn/arbiter.py", line 524, in reap_workers
raise HaltServer(reason, self.WORKER_BOOT_ERROR)
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> ##报错,但看不出具体原因
解决:直接看日志看不出具体的错误, 需要在gunicorn命令后边加上--preload参数,便可查看详细的报错信息
# gunicorn server:app -c gunicorn.conf --preload
然后可以查看日志找出问题
参考:
使用Flask+Gunicorn+Nginx在Linux进行网站部署
www.jianshu.com/p/7da2e5892dd6
Flask+nginx+Gunicorn部署(上 、下)
https://blog.csdn.net/xudailong_blog/article/details/80490137
https://blog.csdn.net/xudailong_blog/article/details/80821326