HAProxy 1.5 - 在 504 错误上提供静态 json 文件

HAProxy 1.5 - Serving static json file on 504 error

我正在尝试设置 HAProxy 以在出现 504 错误时为静态 JSON 文件提供服务器。为了测试,我们将配置文件设置为 10 秒后超时,并使用 errorfile 选项:

defaults
  log     global
  mode    http
  retries 3
  timeout client 10s
  timeout connect 10s
  timeout server 10s
  option tcplog
  balance  roundrobin

frontend https
  maxconn 2000
  bind 0.0.0.0:9000

  errorfile 504 /home/user1/test/error.json

  acl employee-api-service path_reg /employee/api.*
  use_backend servers-employee-api if employee-api-service

backend servers-employee-api
  server www.server.com 127.0.0.1:8000

实际上,我正在尝试在超时时提供 JSON 而不是 HTML,因此后端服务可以优雅地失败。然而,在测试中,我们无法得到任何东西,HTML 或 JSON 都没有。在查看响应时,它只是说它失败了,没有状态代码。我的设置是否适合 errorfile? HAProxy 1.5 支持吗?

根据errorfile的文档:

<file>    designates a file containing the full HTTP response. It is
          recommended to follow the common practice of appending ".http" to
          the filename so that people do not confuse the response with HTML
          error pages, and to use absolute paths, since files are read
          before any chroot is performed.

因此,该文件应包含 完整的 HTTP 响应,但您尝试仅提供 JSON。

文档进一步说明:

For better HTTP compliance, it is
recommended that all header lines end with CR-LF and not LF alone.

示例配置,例如

errorfile 503 /etc/haproxy/errorfiles/503sorry.http

显示错误文件 .http 扩展名的常见做法。

您可以找到一些默认错误文件的示例 here

样本(504.http):

HTTP/1.0 504 Gateway Time-out
Cache-Control: no-cache
Connection: close
Content-Type: text/html

<html><body><h1>504 Gateway Time-out</h1>
The server didn't respond in time.
</body></html>


因此,在您的场景中,504.http 将是这样的:

HTTP/1.0 504 Gateway Time-out
Cache-Control: no-cache
Connection: close
Content-Type: application/json

{
    "message": "Gateway Timeout"
}


此外,您需要将文件大小控制在限制范围内,即 BUFSIZE(8 或 16 KB),如文档中所述。

可能有一些错误日志无法提供您的 JSON 文件。您可能想再次彻底查看 HAProxy 的日志。只是为了确定。