如何防止 502 状态代码作为 haproxy 作为负载均衡器的响应

how to prevent 502 status code as response by haproxy as load balancer

我有 3 个服务器:

server (A)= a nginx(port 80) as reverse proxy to kestler (5000 port)
server (B)= a nginx(port 80) as reverse proxy to kestler (5000 port)
server (C)= a HAProxy as load balancer for port 80 of server (A) and (B)
and server A & B are quite similar.

一切正常,haproxy 将请求转发到服务器 (A) 和 (B),但是如果其中一台服务器(例如 A)中的 kestrel 被杀死,nginx 会响应 502 bad gateway 错误并且 haproxy 不会检测到这个问题并且仍然将请求重定向到它,这是错误的!此时它必须将请求重定向到服务器(B)。

global
    log 127.0.0.1 local2 info
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

defaults
    log global
    mode http
    option httplog
    option dontlognull
    option redispatch
    retries 3
    timeout connect 5s
    timeout client 50s
    timeout server 50s
    stats enable
    stats hide-version
    stats auth admin:admin
    stats refresh 10s
    stats uri /stat?stats

frontend http_front
    bind *:80
    mode http
    option httpclose
    option forwardfor
    reqadd X-Forwarded-Proto:\ http
    default_backend http_back

backend http_back
    balance roundrobin
    mode http
    cookie SERVERID insert indirect nocache
    server ServerA 192.168.1.2:80 check cookie ServerA
    server ServerB 192.168.1.3:80 check cookie ServerB

我该如何解决这个问题? 非常感谢。

您只是在检查 nginx 是否 运行,而不是应用程序是否足够健康可以使用。

backend中添加option httpchk.

option httpchk GET /some/path HTTP/1.1\r\nHost:\ example.com

some path 替换为将证明该应用程序在该服务器上是否可用的路径,如果它 returns 200 OK (或任何 2xx 或 3xx 响应),并替换 example.com 与应用程序期望的 HTTP Host header。

option httpchk

By default, server health checks only consist in trying to establish a TCP connection. When option httpchk is specified, a complete HTTP request is sent once the TCP connection is established, and responses 2xx and 3xx are considered valid, while all other ones indicate a server failure, including the lack of any response.

如果应用程序不健康,这会将服务器标记为不健康,因此 HAProxy 将停止向其发送流量。您需要在每个服务器条目上使用 interdowninterfastinter 选项为每个服务器配置检查间隔,以指定 HAProxy 执行检查的频率。