在本地 - Nginx 容器上的 React App,代理到 Node Express 容器

On local - React App on Nginx container with proxy to Node Express Containers

这应该是非常简单的,但看起来我遗漏了一些非常基本的东西,我们将不胜感激。

我是 运行 我本地 MacBook 上的 POC。基本思想是使用 create-react-app build 脚本构建 React App,并将其部署到本地 nginx-alpine 容器中。我能够做到这一点。我能够访问 index.html 并查看当客户端容器为 运行 时我应该看到的内容。

我在使用 node docker 图像的同一台本地计算机上有一个 node-express 后端 运行。我能够进行设置,并且能够访问这些图像从我的浏览器提供的端点。

问题是当我的反应中的 api 调用这些快速端点时。我已经在我的 nginx.conf 中设置了 proxy_pass 并尝试了多种设置方法。 None 有效。我尝试使用 localhost,厌倦了使用 127.0.0.1,尝试使用 docker 容器的 IP 地址,尝试使用 docker service name,尝试将其设置为 upstream在我的 nginx.conf 中,尝试直接在 proxy_pass 中使用后端 URL。没有任何效果。

这是代码...

http://localhost/ --> 加载 UI

http://localhost:3001/features --> returns 我需要在 UI

上使用的 JSON 负载

http://localhost/admin --> 是我的 UI 上的一个组件,它使用 fetch API 加载路径 /features

nginx.conf

  upstream app_servers {

    server localhost:3001;

}

# Configuration for the server
server {

    # Running port
    listen 80;
    root /usr/share/nginx/html;

    location / {
      try_files $uri /index.html;
    }
    # Proxying the connections connections
    location /features {

        proxy_pass         http://app_servers;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;

    }
}

我的配置文件有什么明显的错误吗?

后端 API 是使用这个 docker-compose 启动的,我认为这不是问题,因为我可以从我的浏览器中很好地使用端点。但这里是无情的。

version: '2'

services:
  thing1:
    image: toggler-backend
    container_name: thing1
    volumes:
      - ./backend:/src/backend
    ports:
      - "3001:3000"

UI的Dockerfile是这个...

FROM nginx:alpine
COPY nginx.conf /etc/nginx

COPY build /usr/share/nginx/html

我现在用 docker run 命令启动 UI。

docker run -it -p 80:80 toggler-client

问题是您的 proxy_pass 在 nginx 容器中 运行ning。 localhost 和 127.0.0.1 都指向 nginx 容器本身。您要做的是到达主机。所以你有以下可能的选择

在proxy_pass

中使用主机IP

您可以在proxy_pass

中使用主机的IP

运行 主机网络上的 nginx 容器

在您的 docker 运行 命令中,您可以在 运行 连接 nginx 容器时添加 --network host。这将确保本地主机指向主机

运行 应用容器网络上的 nginx

您也可以将 nginx 服务添加到您的 docker-compose 并将您的应用程序服务的名称用于 proxy_pass。

或者您可以执行 docker network ls 并找到特定于您的撰写文件的网络。你也可以用那个

我的建议是将其作为撰写文件的一部分。