反向代理模式 Nginx反向代理模块
http、websocket、https > ngx_http_proxy_module
fastcgi > ngx_http_fastcgi_module
uwsgi > ngx_http_uwsgi_module
grpc > ngx_http_v2_module
location / {
proxy_pass http://10.0.0.7:8080;
proxy_intercept_errors on; #负载均衡的情况下开启自定义错误状态码页面的功能
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;#non_idempotent参数POST、LOCK、PATCH也会进行重试
当分配到到服务器出现错误码,平滑转移到资源池到下一个服务器
include proxy_params;
}
#出现500等错误都返回给用户200状态,并跳转至/api
error_page 500 502 503 504 =200 /api;
location = /api{
default_type application/json;
return 200 '{"retCode":"1001","retMsg":"invoke failed"}';
}
proxy_set_header Host $http_host;请求头,不加的话站点不知道请求哪个server
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;显示上一级代理ip和真实ip,每级代理上都需要配置
proxy_set_header X-Real-IP $remote_addr;
set_real_ip_from添加代理服务器ip
real_ip_header X-Forwarded-For从哪个header头检索出需要的ip地址
real_ip_recursive on递归排除set_real_ip_from里面出现的ip,没有出现的是真实ip
proxy_http_version 1.1;
proxy_set_header Connection “”;打开长连接
proxy_connect_timeout 30;代理与后端服务器连接超时时间
proxy_send_timeout 60;后端服务器回传给代理超时时间
proxy_read_timeout 60;代理与后端服务器等待响应超时时间
proxy_buffering on;边传边收
proxy_buffer_size 32k;保存头部信息缓存区大小
proxy_buffers 4 128k;缓存区数量 大小
upstream zh {设置一组
server 172.16.1.7:80;
server 172.16.1.8:80;
}
调度算法
weight 加权轮询,weight值越大,分配到的访问几率越高 weight=值,写后面
ip_hash 每个请求按访问IP的hash结果分配,这样来自同一IP的固定访问一个后端服务器,写上面
url_hash 按照访问URL的hash结果来分配请求,是每个URL定向到同一个后端服务器
least_conn 最少链接数,那个机器链接数少就分发
后端的节点状态指标
状态 概述 写后面
down 当前的server暂时不参与负载均衡
backup 预留的备份服务器
max_fails 允许请求失败的次数
fail_timeout 经过max_fails失败后, 服务暂停时间
max_conns 限制最大的接收连接数
keepalive 16; #最大的空闲连接数
keepalive_timeout 100s; #连接超时时间
keepalive_requests 50; #一个连接最大的请求数