nginx的反向代理upstream失败重试策略详解
作者:IT杂人
文章解析Nginx健康检测参数fail_timeout(标记不可用)与max_fails(失败阈值),并说明重试机制中proxy_next_upstream的配置作用,强调非幂等请求需配合non_idempotent选项,合理设置可避免性能损耗
默认只有被动健康检测
upstream nginxtest{ #默认使用轮询节点分配请求 #max_fails默认=1,fail_timeout默认=10s; server localhost:8080 weight=5 max_fails=2 fail_timeout=5s; server localhost:8082 weight=1 max_fails=2 fail_timeout=5s; } server { listen 18080; server_name localhost; location / { proxy_pass http://nginxtest; #proxy_next_upstream http_500;#默认是error、timeout、幕等请求会重试 root html; index index.html index.htm; } }
- fail_timeout:时间段内计数失败次数
- max_fails:需要fail_timeout时间段统计的失败次数
两个参数说明:在5秒时间段时,处理请求失败2次,则标记为不可用状态
重要的一点说明:fail_timeout还有一个作用,标记为不可用状态的节点,在等待5秒后,会被尝试分配一个请求过来以便检测是否恢复可用状态!!!
默认重试机制
当我们关闭一个节点时,发现nginx还是正常处理了请求,只是某一次请求等待时间变长了
以下为jmeter一秒一次请求,断开一个节点后,发现请求正常,但某一次明显等待长才返回成功
断开节点后,会是网络错误,所以会重试其他节点处理;
重试策略配置
location / { proxy_pass http://nginxtest; proxy_next_upstream error timeout http_404; #off表示不重试 proxy_next_upstream_timeout 6s; proxy_next_upstream_tries 3; }
- proxy_next_upstream :指定哪些状态需要重试,默认开启(off显示关闭),但404/500/post等请求不会重试,除非显示指定;
- proxy_next_upstream_timeout :重试转发超时时间
- proxy_next_upstream_tries:重试次数
非等幂方法(POST、LOCK、PATCH),请求失败后不会再到其他服务器进行重试。加上non_idempotent选项后,即使是非幂等请求类型(例如POST请求),发生错误后也会重试。
不合理的重试策略,会减弱nginx的处理能力
另:代理超时配置
location / { proxy_connect_timeout 20s; proxy_read_timeout 20s; proxy_send_timeout 20s; }
- proxy_connect_timeout :代理连接超时
- proxy_read_timeout:代理超时
- proxy_send_timeout :对应的代理超时
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。