Nginx 的 upstream 目前最常用 前3 种方式
1、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器 down 掉,能自动剔除。
2、weight
指定轮询几率,weight 和访问比率成正比,用于后端服务器性能不均的情况。
3、ip_hash
每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器,可以解决 session 的问题。
而且在高并发情况下,优化了内核,Nginx 可支持高达10w并发连接数的响应。
本次用到的是nginx编译安装最新稳定版1.16,安装传送门点击
下面是相关配置讲解,一般都是在nginx.conf文件里进行配置。
首先给大家说下upstream这个配置的,这个配置是写一组被代理的服务器地址,然后配置负载均衡的算法。
upstream zhuanjie { #定义负载均衡服务器组名称 server 192.168.10.121; server 192.168.10.122; } server { root html; index index.html index.htm; location / { proxy_pass http://zhuanjie; #请求转向反向代理的模块,或者域名,或者外网ip } }
注释:zhuanjie 是模块名字
下面是实战配置
1、热备:如果你有2台服务器,当一台服务器发生事故时,才启用第二台服务器给提供服务。服务器处理请求的顺序:AAAAAA突然A挂啦,BBBBBBBBBBBBBB…..
upstream zhuanjie { server 192.168.10.121; server 192.168.10.122 backup; #热备 }
2、轮询:nginx默认就是轮询其权重都默认为1,服务器处理请求的顺序:ABABABABAB….
upstream zhuanjie { server 192.168.10.121; server 192.168.10.122; }
3、加权轮询:跟据配置的权重的大小而分发给不同服务器不同数量的请求,按照1比2来进行分发。
upstream zhuanjie { server 192.168.10.121 weight=1; server 192.168.10.122 weight=2; }
4、ip_hash:nginx会让相同的客户端ip请求相同的服务器。
upstream zhuanjie { server 192.168.10.121; server 192.168.10.122; ip_hash; }
5.实现负载均衡和动静分离
upstream html { #静态 server 192.168.1.63:80; server 192.168.1.64:80; } upstream php{ #动态 server 192.168.1.65:80; server 192.168.1.66:80; } upstream all { server 192.168.1.62:80; server 192.168.1.63:80; server 192.168.1.64:80; server 192.168.1.65:80; } location / { root html; index index.html index.htm; if ($request_uri ~* \.html$){ proxy_pass http://html; } if ($request_uri ~* \.php$){ proxy_pass http://php;