繁体   English   中英

连接到通过 Nginx 运行 express 的 Nodejs 应用程序时出现 502 Bad Gateway

[英]502 Bad Gateway when connecting to Nodejs app running express through Nginx

我在连接到在端口 8081 上运行的节点应用程序时遇到问题。
我的设置如下(一切都在树莓派上运行):

NGINX

events {
  worker_connections  1024;
}

http {
server {
  root /data/web;

  location / {
  }

  location /pub {
    proxy_pass http://localhost:8081;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}
}

我在第一个位置提供静态文件(这似乎工作正常),我希望第二个位置重新路由到我的节点应用程序。 它在端口 8081 上运行。

我的节点应用程序如下所示:

app.get('/', function(req, res){
  res.send("Hello World!");
});
var server = app.listen(8081, '192.168.0.178');

我正在使用局域网中另一台电脑的简单 wget 测试我的连接:

wget http://192.168.0.178/pub

我得到的完整错误是这样的:

http://192.168.0.178/pub
Connecting to 192.168.0.178:80... connected.
HTTP request sent, awaiting response... 502 Bad Gateway
2018-01-14 15:42:27 ERROR 502: Bad Gateway.

解决方案
接受的答案确实是我遇到的问题。
我添加的另一件事是在我的 /pub 位置重写,因为 '/pub' 需要从转到 Node 应用程序的 url 中切断。 所以最终的 nginx conf 看起来像这样:

http {
access_log /data/access_log.log;
error_log /data/error_log.log debug;

upstream backend {
  server localhost:8081;
}

server {
  root /data/web;

  location / {
  }

  location /pub {
    proxy_pass http://localhost:8081;
    rewrite /pub(.*) /$1; break;
  }
}
}

问题似乎与您暴露 nodejs 应用程序的网络接口有关。 您已将应用程序设置为在具有 ip 192.168.0.178的接口上侦听端口8081 ,但根据说明,nginx 正在通过环回接口进行代理

proxy_pass http://localhost:8081;

您可以解决此问题,将 nodejs 应用程序暴露在环回接口上:

var server = app.listen(8081, 'localhost');

除了应用程序正在运行的机器之外,节点应用程序不应再从任何其他机器的端口 8081 上直接访问

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM