解决 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: ...。
触发根因
- 上游服务返回了非标 HTTP 响应报头(例如包含下划线的非法 Header 键名、或 Header 单行字符数超过 8KB);
- 后端服务在发送响应体中途异常崩溃退出;
- 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,网关成功平滑桥接数据传输。


