【问题标题】:NGINX Bad Gateway 502 on Any Port Except 3000 with NodeJS/Express使用 NodeJS/Express 在除 3000 以外的任何端口上的 NGINX 错误网关 502
【发布时间】:2013-08-12 19:53:51
【问题描述】:

我在几个 NodeJS 实例前面有一个 NGINX 实例(1.4 稳定版)。我正在尝试使用上游模块与 NGINX 进行负载平衡,如下所示:

upstream my_web_upstream {
          server localhost:3000;
          server localhost:8124;
          keepalive 64;
        }



location / {
      proxy_redirect off;
      proxy_set_header   X-Real-IP            $remote_addr;
      proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
      proxy_set_header   X-Forwarded-Proto $scheme;
      proxy_set_header   Host                   $http_host;
      proxy_set_header   X-NginX-Proxy    true;
      proxy_set_header   Connection "";
      proxy_http_version 1.1;
      proxy_cache one;
      proxy_cache_key sfs$request_uri$scheme;
      proxy_pass         http://my_web_upstream;
        }

当端口 3000 的实例不可用时会出现此问题。我从 NGINX 得到一个 502 Bad Gateway。

如果我将上游配置更改为仅指向一个实例,例如 8124,则仍然会出现 502。

运行 netstat 显示 0 个其他应用程序正在侦听我尝试过的任何端口。

为什么 NGINX 报告网关错误?如果其中一个实例关闭,我如何让 NGINX 执行失败?

【问题讨论】:

  • 您确定您的 express 后端运行正常吗?如果直接访问上游端口(@98​​7654322@ 和localhost:8124),是否得到正确的内容?
  • error_log 中有什么内容?

标签: node.js nginx express


【解决方案1】:

如果 netstat 显示你的 nodejs 应用程序没有在端口上运行,那么问题是你还没有启动你的 nodejs 应用程序。

这个 nginx 配置知道如何代理到 nodejs 应用程序,但是如果 nodejs 应用程序还没有启动,你肯定会得到 502。如果要在多个端口上运行它,则必须在每个端口上启动应用程序。因此,不要将端口 3000 硬编码到 NodeJS 代码中,而是让它从环境变量中获取端口,或者使用 pm2 (https://github.com/Unitech/pm2) 等进程管理器生成多个实例。一旦这些运行起来,nginx 就可以代理它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 2019-06-05
    • 2015-08-10
    • 2014-01-30
    • 2017-11-12
    相关资源
    最近更新 更多