nginx 返回 502 Bad Gateway

2023-06-24  本文已影响0人  Always_July

现象描述

客户反馈请求服务时不时的会返回502,返回结果如下。

<html> 
  <head> 
  <title>502 Bad Gateway</title>
  </head> 
  <body> 
  <center><h1>502 Bad Gateway</h1></center> 
  <hr><center>nginx</center> 
  </body>
</html> 

请求流程

一开始以为是我们的nginx服务出现了问题,根据请求URL查询了nginx的access_log和error_log,但是都没有看到该请求。

后来咨询了运维和客户的开发人员,发现他们请求使用了nginx做正向代理,然后公司使用的是openresty。

梳理了一下请求流程如下:


请求流程

由于openresty返回异常的情况带有openresty的文字,所以猜测客户的nginx发生了问题,让客户的开发人员查询相关日志。

客户的nginx日志如下,从日志可以看到是当客户端nginx读取response时,上游关闭了连接。

268057851 upstream prematurely closed connection while reading response header from upstream

上游是阿里云SLB,基本不会出现问题,所以看 openresty的error.log,发现在发生异常的时间范围有很多如下的日志。

openresty error.log 的默认路径:/usr/local/openresty/nginx/logs/

2023/06/19 10:26:59 [alert] 5345#0: 1024 worker_connections are not enough
2023/06/19 10:26:59 [alert] 5345#0: 1024 worker_connections are not enough
2023/06/19 10:26:59 [alert] 5345#0: *5604161168 1024 worker_connections are not enough while connecting to upstream, client: 39.140.131.228, server: xxx.xxx.cn, request: "POST /vas/app/operate/saveTaskPosition HTTP/2.0", upstream: "http://10.12.25.44:25001/injury/app/operate/savePosition", host: "xxx.xxx.cn"
2023/06/19 10:26:59 [alert] 5345#0: 1024 worker_connections are not enough
2023/06/19 10:26:59 [alert] 5345#0: 1024 worker_connections are not enough
2023/06/19 10:26:59 [alert] 5345#0: 1024 worker_connections are not enough

搜索了一下这个问题导致的原因,是nginx 的worker_connections配置的不够。

让运维人员查看了一下配置,使用的还是默认配置1024,修改为10240后持续观察两天发现未出现该问题。
修改 /usr/local/openresty/nginx/conf/nginx.conf

events {
    worker_connections  10240;
}

本地验证

本地使用docker搭建了openstry的环境,配置 worker_connections 为2,curl请求返回
openstry版本:1.13.6

使用windows bash 工具发送url请求

curl localhost/rule  --verbose
*   Trying 127.0.0.1:80...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /rule HTTP/1.1
> Host: localhost
> User-Agent: curl/7.83.1
> Accept: */*
>
* Empty reply from server
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
* Closing connection 0
curl: (52) Empty reply from server

openstry 日志

2023/06/25 07:51:56 [alert] 7#7: 2 worker_connections are not enough
2023/06/25 07:52:53 [alert] 7#7: 2 worker_connections are not enough
2023/06/25 07:53:40 [alert] 7#7: 2 worker_connections are not enough

使用wireshark 抓取 Adapter for loopback traffic capture .
过滤器表达式 tcp.port == 80

wireshark抓包

可以看到三次握手建立后,服务端马上开始四次挥手。

总结

  1. 一定要熟悉请求的流程。
  2. 要先看日志,日志才能看到具体问题的原因。
  3. 事后要持续关注。

参考资料

nginx [alert] worker_connections are not enough

上一篇下一篇

猜你喜欢

热点阅读