flask+uwsgi+openresty(nginx)+linux服务部署---实现负载均衡
一、OpenResty安装
官网下载相应版本源码包:http://openresty.org/en/download.html
1 #准备编译环境 2 yum install pcre-devel openssl-devel gcc curl(centos) 3 apt-get install libpcre3-dev libssl-dev perl make build-essential curl (Ubuntu) 4 5 #编译安装 6 wget https://openresty.org/download/openresty-1.15.8.3.tar.gz 7 tar -xvf openresty-VERSION.tar.gz 8 cd openresty-VERSION/ 9 ./configure 10 make 11 sudo make install 12 13 #添加环境变量 14 vim ~/.bashrc 15 export PATH=/usr/local/openresty/bin:$PATH 16 source ~/.bashrc
测试
resty -e 'print("hello, world")'
启动/停止/重启服务命令(热加载)
#同样添加nginx环境变量 export PATH=/usr/local/openresty/nginx/sbin:$PATH #启动服务 nginx #停止服务 nginx -s stop #热加载 nginx -s reload
二、部署flask程序,使用uwsgi启动
编辑一个最简单的flask程序
app.py
from flask import Flask app = Flask(__name__) @app.route('/test') def index(): return "Hello World!!!"
编辑uwsgi.init
[uwsgi] chdir=./ wsgi-file=app.py callable=app master=true processes=1 threads=1 socket=127.0.0.1:8081 http-keepalive = 1 add-header=Connection: Keep-Alive vacuum=true pidfile=%(chdir)/openresty.pid uid=root gid=root procname-prefix-spaced=openresty logto = ./uwsgi.log chmod-socket = 660 socket-timeout = 600 lazy-apps = true need-app = true worker-reload-mercy=2 reload-mercy=2 #相应字段自己修改
使用uwsgi启动程序
#安装uwsgi pip install uwsgi #通过uwsgi.init配置文件启动 nohup uwsgi --ini uwsgi.ini
#查看进程
ps -ef | grep uWSGI
#测试服务
curl http://localhost:8081/test #Hello World!!!
三、配置nginx
配置/usr/local/openresty/nginx/conf目录下配置文件
nginx.conf
worker_processes auto; worker_cpu_affinity auto; error_log logs/error.log info; pid logs/nginx.pid; events { worker_connections 10240; } http { include mime.types; #default_type application/octet-stream; default_type text/html;
#设置日志格式 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" "$upstream_addr" ' '$upstream_response_time $request_time' access_log logs/access.log main; sendfile on; keepalive_timeout 65; #gzip on; client_max_body_size 6m; client_body_buffer_size 6m; include conf.d/openresty.conf; }
创建conf.d/openresty.conf
upstream openresty_server_backend { server 127.0.0.1:8081; server 127.0.0.1:8082; #转发多套后台服务 #check interval=2000 rise=2 fall=2 timeout=1000 type=http; #check_http_send "HEAD /check.do HTTP/1.1\r\n\r\n"; keepalive 32; } server { listen 8080; # 用于外网访问的nginx端口号 server_name localhost; location / { proxy_pass http://openresty_server_backend; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_connect_timeout 3s; proxy_read_timeout 3s; proxy_send_timeout 3s; proxy_buffer_size 3m; proxy_buffers 8 3m; proxy_set_header Host $host:$server_port; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
配置完重启nginx
在/usr/local/openresty/nginx/logs路径下查看nginx日志