Nginx 到 node.js 的反向代理不起作用

问题描述

我有一个以 Postgres 作为数据库的 angular 和 node 应用程序。我正在将它们部署到 ec2 实例上的 docker 容器。 ec2 上的 Nginx 反向代理不会将请求路由到节点。相同的设置适用于我的本地机器。我收到的错误消息是:“由于访问控制检查,XMLHttpRequest 无法加载 http://localhost:3000/api/user/login”。这是我的 docker-compose 文件

version: '3.3'

networks:
  network1:

services:
  api-service:
    image: backend
    environment:
      PORT: 3000 
    volumes:
      - ./volumes/logs:/app/logs
    ports:
      - 3000:3000
    restart: always
    networks:
      - network1

  Nginx:
    image: frontend
    environment:
      USE_SSL: "false"
    volumes:
      - ./volumes/logs/Nginx:/var/log/Nginx/
      - ./volumes/ssl/Nginx:/etc/ssl/
    ports:
      - 80:80
      - 443:443
    restart: always
    networks:
      - network1

我的Nginx.conf如下:

user  Nginx;
worker_processes  1;

error_log  /var/log/Nginx/error.log warn;
pid        /var/run/Nginx.pid;


http {
    include       /etc/Nginx/mime.types;
    default_type  application/octet-stream;

    server {
        listen       80;
    

        location / {
            root /myapp/app;
            try_files $uri $uri/ /index.html;


            proxy_set_header Upgrade    $http_upgrade;
            proxy_set_header Connection $http_connection;
            proxy_set_header Host       $host;
        }

        location /api/ {
            proxy_pass http://api-service:3000;
        }
    }
}


我的后端 api url 是:(注释行都是我尝试过的)

export const environment = {
  production: false,//apiUrl: 'http://api-service'
  // apiUrl: '/api-service/api'
  // apiUrl : 'http://' + window.location.hostname + ':3000'
  //apiUrl: 'http://localhost:3000/api'
  apiUrl: 'http://localhost:3000'
};

and in my angular service I am using:
const BACKEND_URL = environment.apiUrl + "/api/user/";

and in my backend app.js:

app.use("/api/user/",userRoutes);

我做错了什么?

解决方法

发布对我有用的内容,以防它对某人有所帮助。以下是我将代码移至 ec2 实例时的效果:

导出常量环境 = { 生产:假, //apiUrl: 'http://localhost:3000/api' apiUrl: '/api' };

因此,在 localhost apiUrl 中:'http://localhost:3000/api 有效,但在服务器上无效。