【问题标题】:Nginx reverse proxy map to multiple frontend & backendNginx 反向代理映射到多个前端和后端
【发布时间】:2021-10-13 01:38:25
【问题描述】:

我有一个 Angular 前端和一个 node.js 后端,我想为不同国家的客户部署它们。我们需要为每个国家/地区提供一个前端和后端容器。所以想法是 nginx 应该根据路径重定向到 docker compose 环境中的正确容器:

example.com/us/frontend -> 我们的前端容器

example.com/us/backend -> 我们的后端容器

example.com/fr/frontend -> fr 前端容器

example.com/fr/backend -> fr 后端容器 ...

到目前为止我已经实现了:

docker-compose.yml

version: "3"
services:
  test-proxy:
    container_name: test-proxy
    image: nginx:latest
    depends_on:
      - example-frontend-us # References the service name.
    volumes:
      - ./config/nginx.conf:/etc/nginx/nginx.conf
      - ./content:/usr/share/nginx/html
    ports:
      - 80:80 # Publishs only port 80 outside of docker compose context.

  example-frontend-us:
    container_name: example-frontend-us
    image: angular-frontend
    ports:
      - 8081:80

nginx.conf:

 http {
    server {

        listen 80;
        server_name localhost 127.0.0.1;

        location = / {
            root /usr/share/nginx/html;
            try_files $uri /index.html;
        }
        

        location /us/frontend {
            proxy_pass          http:/example-frontend-us:8081;
            proxy_set_header    X-Forwarded-For $remote_addr;
        }
    }
}

如果我在 localhost/us/frontend 上打开浏览器,我会收到 502 Bad Gateway 响应

如果我在 localhost:8081 上打开浏览器,前端正在工作。

这里有什么问题?如何实现 nginx 路由到正确的容器?

【问题讨论】:

    标签: docker nginx docker-compose


    【解决方案1】:

    在 docker compose 创建的虚拟网络中,您使用内部端口号。所以

    proxy_pass          http:/example-frontend-us:8081;
    

    应该是

    proxy_pass          http://example-frontend-us:80;
    

    (您还缺少 http:// 中的正斜杠)

    最后,你不需要在 example-frontend-us 上映射端口,除非你希望能够直接访问它并绕过 nginx。

    【讨论】:

    • 感谢您的回答。所以我可以从 docker-compose 中删除 -ports 标志并将example-frontend-us 传递给proxy_pass?如果我这样做,我会收到 404 响应。
    • 是的,应该可以。一件事:您的 example-frontend-us 是否回复 /us/frontend/?如果是后者,则需要有一个rewrite 语句来从请求中去除/us/frontend 位。
    • 开/只有 nginx 默认 html 响应。在 /us/frontend 我收到一条 404 消息。但是我发现了一个问题:我将 http:/example-frontend-us 更改为 http:/example-frontend-us/ 现在我得到一个白页而不是 404。似乎我得到了响应。不知道为什么角度前端没有加载。
    • 在控制台中我得到 Uncaught SyntaxError: Unexpected token '
    • 哪个控制台?浏览器控制台?您可以尝试使用 curl 来更“原始”地了解应用返回的内容。