准备的线上服务环境为linux+nginx+gunicorn
准备插件pip install gunicorn gevent
nginx的安装就不在说了,这是就当你已经掌控。这里放出配置
server { listen 80; server_name www.xxx.com; access_log /data/log/flask-shop/access.log; error_log /data/log/flask-shop/error.log; location / { proxy_pass http://127.0.0.1:5000/; # 与下面的gun.conf端口号对应 proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
1. 在项目下面创建所需要的文件
创建gun.conf配置文件,这样方便启动,配置如下:
bind = '127.0.0.1:5000' # 绑定的本地端口号,与上面的nginx配置对应workers = 5 # 进程数,这里设置一般建议CPU * 2 + 1backlog = 2048 #连接数,未处理数据,一般选择2048worker_class = 'gevent' # 工作模式chdir = '/srv/htdocs/flask-shop/' # 加载应用程序之前将chdir目录指定到指定目录daemon = True # 守护Gunicorn进程,默认Falsereload = True # 代码更新时将重启工作,默认为False。此设置用于开发,每当应用程序发生更改时,都会导致工作重新启动。pidfile = chdir + 'rocker.pid' # 设置pid文件的文件名,如果不设置将不会创建pid文件raw_env=["name=test"] # 设置环境变量
2. 配置文件都设置好了,现在制作启动命令了
手打太low了,用命令执行比如 flask server start|stop
来开关应用
import osimport subprocessimport clickdef register(app): @app.cli.command('server', short_help='start web server [start|stop]') @click.argument('type') def server(type): if type == 'start': cmd = 'gunicorn -c gun.conf run:app' message = 'server start success' elif type == 'stop': cmd = 'cat rocker.pid | xargs kill -9' message = 'server stop success' if subprocess.run(cmd, shell=True).returncode: raise Exception('server failed') click.echo(message)
(venv) jyy@a:/srv/htdocs/my app$ flask server start server start success (venv) jyy@a:/srv/htdocs/my app$ flask server stop server stop success
可以ps -auxf|grep gunicorn
去应证
单个web运行可以这样了,但是网站多了,应用多了,这样不就烦死了。所以给这东西加个壳来管理,supervisor出场了。
作者:七霸刀
链接:https://www.jianshu.com/p/3bdd27fcb7ee