DEBUG.WIKI
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证

解决 Kong API Gateway 报错 502 Bad Gateway 响应格式修复

排查 Kong API 网关代理接口返回 {"message":"An invalid response was received from the upstream server"},排查 upstream keepalive 与超时。

问题现象

通过 Kong 网关路由请求微服务接口时,客户端返回 502 错误:

{
  "message": "An invalid response was received from the upstream server"
}

Kong 的 error.log 日志打印:upstream sent invalid response: ...。

触发根因

  1. 上游服务返回了非标 HTTP 响应报头(例如包含下划线的非法 Header 键名、或 Header 单行字符数超过 8KB);
  2. 后端服务在发送响应体中途异常崩溃退出;
  3. Kong 的 upstream_read_timeout 超时断开。

解决步骤

1. 放宽 Kong Service 的读取与连接超时

通过 Kong Admin API 调整目标 Service 的超时属性:

curl -X PATCH http://localhost:8001/services/my-service \
  --data "connect_timeout=10000" \
  --data "write_timeout=60000" \
  --data "read_timeout=60000"

2. 在 kong.conf 中允许非标请求头与调大缓冲区

编辑 /etc/kong/kong.conf:

nginx_http_large_client_header_buffers = 4 16k
nginx_http_ignore_invalid_headers = off

重启生效:

kong reload

验证确认

再次向目标路由发送包含复杂 Header 的业务请求:

接口返回 HTTP/1.1 200 OK,网关成功平滑桥接数据传输。