nginx+gunicorn+flask部署python服务

nginx

安装nginx,在 /usr/local/nginx 目录下, 修改conf文件夹下的 nginx.conf 文件

server {
        # python server
        listen       8088;
        server_name  localhost;
		
    	location / {
            proxy_pass http://127.0.0.1:5000;
        }
    }

启动nginx

>/usr/local/nginx/sbin/nginx

flask

新建server.py并写入

from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET'])
def hello():
    return 'hello'
if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0',port=5000)

gunicorn

命令行进入server.py所在目录

  • 开启gunicorn进程:

gunicorn -w worker数量 -b ip:端口号 运行文件名:flask实例名

gunicorn -D -w 3 -b 127.0.0.1:5000 server:app
  • 关闭gunicorn:

先找到gunicorn的pid

pstree -ap | grep gunicorn

然后杀死进程(假设17556为pid)

kill -9 17556

说明

gunicorn命令的参数:

  • D 表示后台运行
  • w 表示有3 个 工作线程(感觉有些类似 nginx 的 master-worker 模型)
  • b 指定ip 和端口
  • 这里采用本机访问, 主要是为了使用nginx 进行代理, 方便管理
  • application 表存放 写着全局变量 app 的那个工程文件夹
  • 在我们的这个工程中, 即包含server.py 的那个文件,app 为全局变量 (app = Flask(name))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章