后端服务器为2台iis,要通过nginx实现负载均衡功能。并实现健康监测。
1、定义upstream:
在nginx主配置文件http {} 段中配置如下:
upstream iis { ip_hash; server 192.168.1.11 max_fails=3 fail_timeout=20s; server 192.168.1.12 max_fails=3 fail_timeout=20s; }
ip_hash 通过ip_hash实现会话保持。
max_fails=3 请求失败次数,超过时返回proxy_next_upstream定义的错误。
fail_timeout 在max_fails失败时,停止服务的时间。
2、定义服务:
server { listen 80; server_name www.test.com; index index.html; location / { proxy_pass http://iis; proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header; include /usr/local/nginx/conf/proxy.conf; } }
proxy_next_upstream 当分发到会话的服务器出现500,502,503,504,超时错误时,转发到另一台,实现故障转移
3、编辑代理配置文件:/usr/local/nginx/conf/proxy.conf
proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k;
proxy_set_header实现转发客户端ip到后端服务器。
当在内网环境测试时,会发现不管几台机器访问nginx负载均衡,会话总是分发到一台机器,除非那台机器宕机,会话才分发到第二台,后来查资料说:The key for the hash is the class-C network address of the client. 意思说来自同一网段的ip会话都会分发到一台机器。类似于网络地址hash了。而不是ip地址hash。
原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/2693.html