几个工具的关系结构如下
请求 -> Nginx -> supervisor进程管理[gunicorn、gevent容器[flask]]
安装
pip install gunicorn gevent flask
一、flask应用
# -*- coding: utf-8 -*- # run.py from flask import Flask from werkzeug.middleware.proxy_fix import ProxyFix app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1) @app.route('/') def hello_world(): return 'Hello World!'
二、gunicorn+gevent配置
命令行启动
gunicorn -w 2 -b 127.0.0.1:8000 run:app
配置文件
# -*- coding: utf-8 -*- # config.py from __future__ import print_function, absolute_import, unicode_literals import multiprocessing import os import gevent.monkey gevent.monkey.patch_all() if not os.path.exists('log'): os.mkdir('log') # debug = True loglevel = 'debug' bind = "0.0.0.0:5000" pidfile = "log/gunicorn.pid" accesslog = "log/access.log" errorlog = "log/debug.log" daemon = True # 启动的进程数 workers = multiprocessing.cpu_count() * 2 + 1 worker_class = 'gevent' x_forwarded_for_header = 'X-FORWARDED-FOR'
指定配置文件启动
gunicorn -c config.py run:app
关闭
# 查看PID号 ps -ef | grep gunicorn # 或者 cat log/gunicorn.pid # 停止 kill -9 PID号 # 重启 kill -HUP PID号
整合成命令行 service.sh
此方法仅为参考,可以使用supervisor管理进程
#!/bin/bash # service.sh # 添加启动命令 function start(){ echo "start..." # 此处修改为项目路径 gunicorn -c config.py app:app echo "start successful" return 0 } # 添加停止命令 function stop(){ echo "stop..." kill -9 `cat log/gunicorn.pid` echo "stop successful" return 0 } # 重启 function restart(){ echo "restart..." kill -HUP `cat log/gunicorn.pid` echo "restart successful" return 0 } case $1 in "start") start ;; "stop") stop ;; "restart") restart ;; *) echo "请输入: start, stop, restart" ;; esac
三、supervisor配置
[program: myweb] command=python server.py directory=/home/python/tornado_server
开机自启
四、Nginx配置
server { listen 80; server_name _; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { proxy_pass http://127.0.0.1:5000/; 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; } }