首页 > 解决方案 > Nginx 反向代理到后端给出错误 ERR_CONNECTION_REFUSED

问题描述

我有一个应用程序在 EC2 实例的端口 6001(前端,由 react.js 构建)和端口 6002(后端,由 node.js 构建)的服务器上运行。

当我通过实例中的 ubuntu 终端发送请求时curl -X GET http://127.0.0.1:6002/api/works,它工作正常,我得到了正确的数据。

现在我使用域 ( http://example.com) 访问浏览器。但是,我只让前端被调用。当我在浏览器上向后端服务器发送请求时,它给了我一个错误GET http://127.0.0.1:6002/api/works net::ERR_CONNECTION_REFUSED(域通过 ELB)

这是我的 nginx 配置。

server {
        listen 80;
        listen [::]:80;

        server_name example.com;

        root /home/www/my-project/;
        index index.html;

        location / {
                proxy_pass http://127.0.0.1:6001/;
        }

        location /api/ {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;
                proxy_redirect off;
                proxy_pass http://127.0.0.1:6002/;
                proxy_set_header X-Real-IP $remote_addr;
        }
}

我的情况与类似,他/她说

My entry point via the aws dns takes me to the React app 127.0.0.1:4100 that is the port 80 nginx is listening to. The react app is the one that makes the backend calls and it is coded to make the backend api calls on 127.0.0.1:1323/api. The client error you saw was because it is displaying what the react app is trying to call in the server, but nginx is not redirecting that call to the app that is running at that port. Does that make sense?

选定的答案对我不起作用。

另外,根据评论,问题是通过http://AWS_IP/在反应应用程序上发送请求来解决的。但我不确定这对我来说是否是一个好的解决方案,因为没有必要使用 ELB?如果我理解ELB的概念对吗?我认为请求需要通过 ELB 完成?

请帮忙,这让我发疯了。

标签: nginxamazon-ec2

解决方案


从你的问题中,我明白了以下几点,

  1. 您的域指向 Amazon ELB
  2. 这个ELB后面有一个VM,里面有Nginx和2个应用程序。
  3. Nginx 监听 80 端口,后端应用监听 6002 端口,前端监听 6001 端口

  4. 您的前端应用程序正在使用 http://127.0.0.1:6002/api/works从本地浏览器调用后端

问题来了,

您可以从运行应用程序的同一实例(侦听端口 6001)卷曲 127.0.0.1,因为您正在访问该实例的本地主机,并且当您的 Web 应用程序在本地浏览器上运行时它是不同的,因为您的反应应用程序(所有javascript 应用程序)在您的本地计算机中执行,对于后端调用,它正在访问 localhost(在您的情况下)并返回 CONNECTION REFUSED。

所以解决方案是您必须更改后端 URL,使其看起来像http://yourdomain/api/works

除此之外,我对您的配置有一些建议。

  1. 您的前端不需要单独的 Web 服务器,因为您可以使用相同的 Nginx。
  2. 确保您的 ELB 目标端口是 80 或 NGINX 正在侦听的同一端口。
  3. 并关闭端口 6001 和 6002(如果可公开访问)

推荐阅读