【问题标题】:On local - React App on Nginx container with proxy to Node Express Containers在本地 - 在 Nginx 容器上使用代理到 ​​Node Express 容器的 React App
【发布时间】:2018-01-14 06:29:40
【问题描述】:

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

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

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

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

这里是代码...

http://localhost/ --> 加载用户界面

http://localhost:3001/features --> 返回我需要在 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

【问题讨论】:

    标签: node.js reactjs docker nginx reverse-proxy


    【解决方案1】:

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

    在 proxy_pass 中使用主机 IP

    你可以在proxy_pass中使用你主机的IP

    在主机网络上运行 nginx 容器

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

    在应用的容器网络上运行 nginx

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

    或者您可以通过docker network ls 找到特定于您的撰写文件的网络。你也可以用它

    我的建议是让它成为撰写文件的一部分。

    【讨论】:

    • 谢谢塔伦。我会试试的,让你知道。我有一种预感,这与你提到的有关。我不知道的是解决方案。你给了我选择。我会尽快尝试。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多