nginx四层、七层负载均衡配置示例
所谓四层就是基于IP+端口的负载均衡,通过虚拟IP+端口接收请求,然后再分配到真实的服务器;七层通过虚拟的URL或主机名接收请求,然后再分配到真实的服务器七层就是基于URL等应用层信息的负载均衡。
七层负载
# 定义 upstream phpserver { server192.168.2.3; server192.168.2.4; } upstream htmlserver { server192.168.2.1; server192.168.2.2; } # 引用 location / { root /usr/share/nginx/html; index index.html index.htm; if ($request_uri ~*\.html$){ proxy_pass http://htmlserver; } if ($request_uri~* \.php$){ proxy_pass http://phpserver; } }
四层负载
stream { log_format proxy ‘$remote_addr $remote_port - [$time_local] $status $protocol ‘ ‘"$upstream_addr" "$upstream_bytes_sent" "$upstream_connect_time"‘ ; access_log /var/log/nginx/proxy.log proxy; upstream lb { server 172.16.1.5:80 weight=5 max_fails=3 fail_timeout=30s; server 172.16.1.6:80 weight=5 max_fails=3 fail_timeout=30s; } server { listen 80; proxy_connect_timeout 3s; proxy_timeout 3s; proxy_pass lb; } }