nginx
主页 > 服务器 > nginx >

Nginx之upstream被动式重试机制的实现

2025-03-02 | 佚名 | 点击:

我们使用Nginx通过反向代理做负载均衡时,如果被代理的其中一个服务发生错误或者超时的时候,通常希望Nginx自动重试其他的服务,从而实现服务的高可用性。实际上Nginx本身默认会有错误重试机制,并且可以通过proxy_next_upstream来自定义配置。

Nginx 通过 proxy_next_upstream 参数来定义什么情况下会被认为是 fails,从而触发失败重试机制。

fails 可以分成两类:

默认错误

出现 error 的场景,常见的是上游服务器的服务重启、停止,或者异常崩溃导致的无法提供正常服务。而 timeout 的情况,就是代理请求过程中达到对应的超时配置,主要包括了:

选择定义错误

异常状态码部分(就是 4xx、5xx 错误)。上游服务器返回空响应或者非法响应头

invalid_header: a server returned an empty or invalid response;

其默认值是proxy_next_upstream error timeout,即发生网络错误以及超时,才会重试其他服务器。默认情况下服务返回500状态码是不会重试的

指令配置

proxy_next_upstream

设置当连接upstream服务器集群中的某个服务器第一次失败时,指定在哪些情况下将请求传递到下一个服务器

1

2

3

语法: proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | http_429 | non_idempotent | off ...;

默认: proxy_next_upstream error timeout;

使用位置:   http, ,serverlocation

当请求类型是POST时,Nginx默认不会失败重试,如果想让POST请求也会失败重试,需要配置non_idempotent。

配置示例:

代码语言:javascript

1

2

3

4

5

6

7

8

9

10

11

upstream nginxretry {

    server 127.0.0.1:9030 weight=10;

    server 127.0.0.1:9031 weight=10;

}

server {

    listen 9039;

    location / {

        proxy_pass http://nginxretry;

        proxy_next_upstream error timeout http_500;

    }

}

proxy_next_upstream_timeout

设置重试的超时时间,超时后不再重试,给用户返回错误,默认为0,即不做限制

语法:

proxy_next_upstream_timeout time;

Default:

proxy_next_upstream_timeout 0;

Context:

http, server, location

proxy_next_upstream_tries

设置重试的最大次数,若超过重试次数,也不再重试,默认为0,即不做限制(proxy_next_upstream_timeout时间内允许proxy_next_upstream_tries次重试,包括第一次)

语法:

proxy_next_upstream_tries number;

Default:

proxy_next_upstream_tries 0;

Context:

http, server, location

配置示例:

1

2

3

4

5

server {

    proxy_next_upstream error timeout;

    proxy_next_upstream_timeout 15s;

    proxy_next_upstream_tries 5;

}

重试限制方式

默认配置是没有做重试机制进行限制的,也就是会尽可能去重试直至失败。

Nginx 提供了以下两个参数来控制重试次数以及重试超时时间:

对upstream中某单一服务器的限制

配置示例1:

1

2

3

4

upstream httpget {

    server 192.168.111.101:8080 max_fails=5 fail_timeout=10s;

    server 192.168.111.102:8080;

}

配置示例2:

1

2

3

4

5

6

7

8

9

proxy_connect_timeout 3s;

proxy_next_upstream_timeout 6s;

proxy_next_upstream_tries 3;

 

upstream test {

    server 127.0.0.1:8001 fail_timeout=60s max_fails=2; # Server A

    server 127.0.0.1:8002 fail_timeout=60s max_fails=2; # Server B

    server 127.0.0.1:8003 fail_timeout=60s max_fails=2; # Server C

}

原文链接:
相关文章
最新更新