Nginx配置说明

upstream 配置
upstream backend{
server 192.168.1.11:8080 weight=1;
server 192.168.1.12:8080 weight=2;
}
权重:使用weight来配置,默认为1,权重越高分配的请求就越多
然后使用proxy_pass来处理用户请求
location / {
proxy_pass http://backend;
}
负载均衡算法
负载均衡用来解决用户请求到来时如何选择upstream server,默认采用轮询round-robin

round-robin:轮询,以轮询方式将请求转发到上游服务器,通过配合weight配置实现基于权重的轮询
ip_hash:根据客户IP进行负载均衡,将相同IP负载均衡到同一个upstream server
upstream backend{
ip_hash;
server 192.168.1.11:8080 weight=1;
server 192.168.1.12:8080 weight=2;
}
hash key [consistent]: 对某个key进行哈希或者使用一致哈希算法进行负载均衡
哈希算法
upstream backend{
hash $uri
server 192.168.1.11:8080 weight=1;
server 192.168.1.12:8080 weight=2;
}
哈希一致性算法
upstream backend{
hash $consistent_key consistent;
server 192.168.1.11:8080 weight=1;
server 192.168.1.12:8080 weight=2;
}
least_conn:将请求负载均衡到最少活跃连接的上游服务器.
least_time:最小平均响应时间进行负载均衡(商业版提供)
失败重试
通过配置max_fails和max_timeout来指定每个上游服务器失败次数

upstream backend {
server 192.168.1.11:8080 max_fails=2 fail_timeout=10s weight=1;
server 192.168.1.12:8080 max_fails=2 fail_timeout=10s weight=1;
}

location /{
proxy_connect_timeout 5s;
proxy_read_timeout 5s;
proxy_timeout 5s;

proxy_next_upstream error timeout;
proxy_next_upstream_timeout 10s;
proxy_next_upstream_tries 2;
proxy_pass http://backend;
add_header upstream_add $upstream_add;

}
TCP心跳检查
interval:监测时间间隔
fall:监测失败多少次后上游服务器被标识为不存活
rise:检测成功多少次后上游服务器被标识为存活,并可以处理请求
timeout:监测请求超时时间配置
upstream backend{
server 192.168.1.11:8080 weight=1;
server 192.168.1.12:8080 weight=2;
check interval=3000 rise=1 fall=3 timeout=2000 type=tcp;
}
HTTP心跳检查
check_http_send:检查时发送HTTP请求内容
check_http_expect_alive:服务器返回匹配响应状态码
upstream backend{
server 192.168.1.11:8080 weight=1;
server 192.168.1.12:8080 weight=2;

check interval=3000 rise=1 fall=3 timeout=2000 type=http;
check_http_send "HEAD /status HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;

}
注意:检查时间间隔不能太短,否则可能因为心跳检查包太多导致服务器挂掉
本文使用的是openresty/1.11.2.1(对应nginx-1.11.2),安装之前需要打nginx_upstream_check_module补丁(check_1.9.2+.patch)到Nginx目录下执行shell:

patch -p0</usr/servers/nginx_upstream_check_module-master/check_1.9.2+.patch

如果不安装补丁,那么ngixn_upstream_check_module模块是不工作的,建议使用wireshark抓包查看是否工作.

原文信息

作者:乐楽樂
链接:https://www.jianshu.com/p/55aee46a8a0c
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/fzw-/p/8972873.html