简体   繁体   English

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

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

I'm having issues connecting to my node app that is running on port 8081.我在连接到在端口 8081 上运行的节点应用程序时遇到问题。
My setup is as follows (everything runs on a Raspberry Pi):我的设置如下(一切都在树莓派上运行):

NGINX 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;
  }
}
}

I'm serving static files with the first location (which seems to be working fine), and I would like the second location to reroute to my node app.我在第一个位置提供静态文件(这似乎工作正常),我希望第二个位置重新路由到我的节点应用程序。 which is running on port 8081.它在端口 8081 上运行。

My node app looks like this:我的节点应用程序如下所示:

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

And I'm testing my connection using a simple wget from another pc in the LAN:我正在使用局域网中另一台电脑的简单 wget 测试我的连接:

wget http://192.168.0.178/pub

The full error I get is this:我得到的完整错误是这样的:

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.

SOLUTION解决方案
The accepted answer was indeed the problem I was having.接受的答案确实是我遇到的问题。
Another thing I added was a rewrite in my /pub location because '/pub' needs to be cut off from the url going to the Node app.我添加的另一件事是在我的 /pub 位置重写,因为 '/pub' 需要从转到 Node 应用程序的 url 中切断。 So the final nginx conf looks like this:所以最终的 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;
  }
}
}

The problem seems related to the network interface you are exposing the nodejs app.问题似乎与您暴露 nodejs 应用程序的网络接口有关。 You have setup the app to listen to port 8081 on the interface with ip 192.168.0.178 , but the nginx is proxying trough the loopback interface, given the instruction您已将应用程序设置为在具有 ip 192.168.0.178的接口上侦听端口8081 ,但根据说明,nginx 正在通过环回接口进行代理

proxy_pass http://localhost:8081;

You can solve this issue exposing the nodejs app on the loopback interface:您可以解决此问题,将 nodejs 应用程序暴露在环回接口上:

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

The node app should be no more reachable directly on port 8081 from any other machine except the one the app is running除了应用程序正在运行的机器之外,节点应用程序不应再从任何其他机器的端口 8081 上直接访问

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

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