Nginx+Gunicorn部署Flask应用

记录一次 Nginx+Gunicorn 部署简单 Flask 应用的爬坑历程,以备以后之用
因为是第一次接触 Nginx 和 Gunicorn,用了一天才配置完毕。

运行配置

三台Ubuntu LTS 16.04 机器:
web1: 192.168.0.130:5001
web2: 192.168.0.131:5001
web3: 192.168.0.132:5001
负载均衡服务器:192.168.0.130:5000

Flask测试小程序:

先写个小的

import socket
from flask import Flask, jsonify
app = Flask(__name__)
times = [0,0]


def get_host_ip():
    """
    查询本机ip地址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    except Exception:
        pass
    finally:
        s.close()

    return ip


@app.route('/',methods = ['get','post'])
def hello():
    times[0] += 1
    info = "hello index: %s: %s times"%(get_host_ip(),times[0])
    print('run hello()')
    return info

@app.route('/test',methods = ['get','post'])
def test():
    times[1] += 1
    info = "hello test: %s: %s times" % (get_host_ip(), times[1])
    print('run test()')
    info_dict = {'info':info}
    return jsonify(info_dict)
if  __name__ == "__main__":
    app.run(debug=True) #本机测试

上述文件为 main.py,获取服务器的 ip 是为了测试负责均衡是否起作用。

安装Gunicorn

直接安装即可:pip install gunicorn
配置文件:

import gevent.monkey
gevent.monkey.patch_all()

import multiprocessing

debug = True
loglevel = 'debug'
bind = '192.168.0.130:5001' #不同机器上的 ip 不同
pidfile = 'gunicorn.pid'
accesslog = 'log.out/gunicorn_access.log'
errorlog = 'log.out/gunicorn_error.log'
daemon = 'false'
#启动的进程数
workers = 1
worker_class = 'gunicorn.workers.ggevent.GeventWorker'
worker_connections = 1024
x_forwarded_for_header = 'X-FORWARDED-FOR'

上述文件为 web1 上的 conf.py
启动服务:

gunicorn -c conf.py main:app &

测试一下是否可以正常使用,确保没有错误。

安装Nginx

直接安装即可:sudo apt-get install nginx
1、配置 conf 文件(这里直接在/ect/nginx/nginx.conf上进行的修改,不建议如此操作)

user nginx;
worker_processes auto;
pid /run/nginx.pid;
events {
        worker_connections 1024;
        # multi_accept on;
}

http {
        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

                ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;
        gzip_disable "msie6";

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
        # 后端服务器
        upstream backend_server   {
             server   192.168.0.130:5001  weight=1 max_fails=2 fail_timeout=30s;
             server   192.168.0.131:5001  weight=1 max_fails=2 fail_timeout=30s;
             server   192.168.0.132:5001  weight=1 max_fails=2 fail_timeout=30s;
        }
}

2、修改 sites-available/default 文件

server {
        listen 5000 default_server;
        listen [::]:5000 default_server;
        server_name _;
        location /{
                proxy_pass http://backend_server/;
                proxy_redirect  off;
                proxy_set_header   Host                 $http_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;
                # 一定要去掉默认的那句 try_files,否则无法进行代理
       }
}

然后重启或者重新加载配置文件

sudo servcie nginx restart

到这里就部署完毕了。

你可能感兴趣的:(Python)