首页 > 解决方案 > HAProxy 1.5 - 在 504 错误上提供静态 json 文件

问题描述

我正在尝试设置 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 支持这个吗?

标签: jsonerror-handlingtimeouthaproxy

解决方案


根据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显示了错误文件扩展的常见做法。

您可以在此处找到一些默认错误文件的示例。

示例(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 的日志。只是要确定。


推荐阅读