flask的web应用使用gunicorn+nginx部署示例

安装nginx

flask 应用示例

requirements.txt内容如下:

click==6.6
Flask==0.11.1
gunicorn==19.6.0
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
pkg-resources==0.0.0
Werkzeug==0.11.11

激活虚拟环境后, 执行:

pip install -r requirements.txt

安装需要的库。

编写flask的web应用, 代码如下:

# -*- coding: utf-8 -*-

from flask import Flask, jsonify, session, request

app = Flask(__name__)
app.secret_key = 'super secret key'

@app.route('/', methods=['GET'])
def index():
    return jsonify({'k': 'v'})

@app.route('/test', methods=['GET'])
def test():
    num = request.args.get('num')
    old = session.get('num') or None
    session['num'] = num
    return jsonify({'ret': old})


if __name__ == '__main__':
    print 'Started'
    app.run(host='0.0.0.0')

启动gunicorn

Gunicorn (独角兽)是一个高效的Python WSGI Server,通常用它来运行 wsgi application 或者 wsgi framework(如Django,Flask),地位相当于Java中的Tomcat。

Gunicorn 'Green Unicorn(绿色独角兽)' is a Python WSGI HTTP Server for UNIX. It's a pre-fork worker model ported from Ruby's Unicorn project(从Ruby的Unicorn移植而来). The Gunicorn server is   broadly compatible with various web frameworks, simply implemented, light on server resources, and fairly speedy.

在两个命令行窗口中, 分别执行:

gunicorn -b 127.0.0.1:8000  app:app

gunicorn -b 127.0.0.1:8001  app:app

也可以通过一条命令, 监听两个端口:

gunicorn -b 127.0.0.1:8000 -b 127.0.0.1:8001 app:app

这个时候,访问:

http://localhost:8001/

http://localhost:8000/

都可以看到:

{
     "k": "v"
}

的输出。

验证

假设启动两个gunicorn,会启动两个app实例, 分别服务端口8000和8001, 那么

1、 首先访问:

http://localhost:8000/test?num=8000

此时, 会返回:

{
    "ret": "null"
}

2、 接着访问:

http://localhost:8001/test?num=8001

如果存在两个app实例, 那么应该返回:

{
    "ret": "null"
}

但实际上, 返回的是:

{
    "ret": "8000"
}

说明只启动了一个app实例。

nginx的负载均衡配置

修改nginx的nginx.conf配置文件(最好先做个备份)。 在http节点, 添加:

# 测试
upstream app {   
    server 127.0.0.1:8000; 
    server 127.0.0.1:8001; 
}

在server节点, 添加:

    location / { 
        proxy_pass        http://app;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }

重启nginx

sudo  nginx -s reload

访问

这个时候, 访问

http://localhost/

即可看到:

{
     "k": "v"
}

负载均衡的部署就完成了。

此外, 还可以使用supervisor来监控gunicorn进程(略)。

本文来自网易实践者社区,经作者王一兵授权发布。