python3.6+gunicorn+supervisor部署flask项目
发布时间
阅读量:
阅读量
1. 服务器环境:
ubuntu
python3.6
2. 开发接口:
from flask import request, Flask
app = Flask(__name__)
@app.route('/test', methods=['get'])
def test_view():
return '123'
if __name__ == "__main__":
app.run(port=8000, debug=True, host='0.0.0.0')
AI写代码
3. 使用gunicorn作为wsgi容器
- 安装gunicorn:pip install gunicorn
- 启动gunicorn:gunicorn -w4 -b0.0.0.0:8000 test:app,其中-w表示worker数量,-b表示监听地址,test是接口文件的名字,app是文件中创建的app,启动时默认为同步,如果要开启异步需要安装gevent,启动命令中添加参数-k gevent;启动后实在当前终端下运行,如果control+c会直接结束gunicorn进程,如果要在后台运行,添加参数-D,gunicorn -w4 -D -k gevent -b0.0.0.0:8000 test:app;如果不想在启动时输入这么多参数,可以将参写入配置文件中,每次启动时用-c传入配置文件启动,例如:新建文件gun.conf,编辑如下内容:
import os
bind = ‘0.0.0.0:8000’ #绑定的ip及端口号
workers = 4 #进程数
backlog = 2048 #监听队列
worker_class = “gevent” #使用gevent模式,还可以使用sync 模式,默认的是sync模式
debug = True
chdir = ‘/root/my_project/scfp_confirm’ # test文件路径
proc_name = ‘gunicorn.proc’
启动命令:gunicorn -c test:app
4. 使用supervisor进行进程管理
- 安装supervisor:pip install supervisor,大部分网上博客是说在服务器中使用apt-get或者yum安装,这些方式安装的是3.x版本,只支持使用python2运行,但是现在使用pip进行安装为4.x版本,可以支持python3,安装成功后在/etc/supervisor/conf.d中创建一个配置文件,如:test.conf,编辑如下内容:
[program:fpconfirm] # 程序名称,可以随便写
command=/root/venv/test/bin/gunicorn -c gun.conf fp_api:app # 启动gunicorn的命令,需要加上gunicornde路径
directory=/root/my_project/scfp_confirm # test文件路径
autostart=true # 服务器启动后supervisor自动启动
autorestart=true # 程序挂掉后自动重启
stdout_logfile=/var/log/gunicorn/gunicorn_supervisor.log # gunicorna日志文件,这两个文件路径supervisor不会自动创建,需要手动创建
stderr_logfile=/var/log/gunicorn/gunicorn_supervisor_err.log- 修改/etc/supervisor/supervisor.conf:
[inet_http_server] ; inet (TCP) server disabled by default
port=0.0.0.0:9001 ; 这是进程管理的地址,将原来127.0.0.1该为0.0.0.0后可以在外网访问并管理进程
username=user ; 登录进程管理的用户名和密码,可以自己设置
password=123
[include]
files = /etc/supervisor/conf.d/*.conf ; 这里表示在启动时加载conf.d中的所有.conf文件,这样可以同时管理多个程序的配置文件- 启动命令:supervisord -c /etc/supervisor/supervisord.conf
全部评论 (0)
还没有任何评论哟~
