如何修复 NGINX 502 Bad Gateway 错误?

use*_*861 5 nginx websocket http-status-code-502

我正在一个有角度的应用程序中研究网络套接字。我让它通过 nginx 连接到 python 后端。我发现大约 90% 的时间我都会收到 502“Bad Gateway”错误。我会这样做:

  1. 在浏览器中加载页面并连接 Web 套接字
  2. Python后端发送数据到Angular前端
  3. 断开网络套接字
  4. 尝试重新连接 Web 套接字 <-- 502 Bad Gateway 错误
  5. Chrome 中的硬重载
  6. 在浏览器中加载页面并连接 Web 套接字 <-- 没有 502 错误

我不明白为什么会发生这种情况。我不知道为什么会收到 502 错误。我也无法弄清楚为什么进行硬重新加载可以解决问题。我尝试过的事情:

  • 增加 nginx 日志级别以进行调试。日志仍然没有任何有用的信息。
  • 我不保留任何网络套接字对象的状态。我这样做是为了防止某些东西被缓存在某个地方。
  • 我总是使用关闭代码 1000 关闭网络套接字
  • 我在服务器上手动运行python服务,以便可以观看。当502错误发生时,服务不会显示任何异常。
  • 将nginx max_fails 设置为0。将fail_timeout 设置为0。这些更改似乎都没有任何效果。(我在其他答案中找到了这个建议)

我应该寻找什么来帮助我解决这个问题?

编辑:这是我的 nginx conf.d 文件:

server {
  listen  80;

  index index.html;
  root /var/www/mysite;

  location / {
    access_log  /var/log/nginx/mysite/ui.access.log;
    error_log /var/log/nginx/mysite/ui.error.log;
    try_files $uri $uri/ /index.html;
  }

  location /ws/ {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header Host $proxy_host;
    proxy_pass http://WEBSOCKET/;
    access_log  /var/log/nginx/mysite/ws_services.access.log;
    error_log /var/log/nginx/mysite/ws_services.error.log;
    proxy_read_timeout 300s;
  }
}

upstream WEBSOCKET {
    ip_hash;
    server 127.0.0.1:8765;
}
Run Code Online (Sandbox Code Playgroud)

Dom*_*erg 4

与OP遇到的问题不一样,但以防万一有人遇到这个问题并且具有与我相同的设置:

我在 SSL(so 协议)上使用 WebSockets wss://,并且弹出了 502,即使配置之前已经工作过。配置如下:

...
proxy_pass http://127.0.0.1:8080;
...
Run Code Online (Sandbox Code Playgroud)

在后端,我使用带有ws包的 Node 来创建 websocket 服务器

正如我所说:以前可以工作,但突然停止工作了。另外,nginx 将upstream prematurely closed connection while reading response header from upstream错误写入错误日志中。我认为 nginx 或节点解决了某种安全问题,导致设置不再工作。

为了使它工作,我必须做的是使用 https 而不是 http 进行proxy_pass配置

...
proxy_pass https://127.0.0.1:8080;
...
Run Code Online (Sandbox Code Playgroud)