【问题标题】:How to connect back-end with front-end using ngnix in Kubernetes如何在 Kubernetes 中使用 nginx 连接后端和前端
【发布时间】:2019-07-19 17:03:50
【问题描述】:

我在 Kubernetes 中部署了一个后端服务(http://purser.default.svc.cluster.local:3030)和一个前端 angular 6 应用程序,nginx.conf

upstream purser {
  server purser.default.svc.cluster.local:3030;
}

server {
  listen 4200;

  location / {
   proxy_pass http://purser;
   root /usr/share/nginx/html/appDApp;
   index index.html index.htm;
   try_files $uri $uri/ /index.html =404;
  }
}

在角码中我们使用http.get('http://purser.default.svc.cluster.local:3030', {observe: 'body', responseType: 'json'})

案例1:在nginx.conf 中设置proxy_pass,当我们点击ui 服务时,它会重定向到后端并直接从后端提供json 输出。

案例2:没有proxy_pass,当我们点击前端服务时,它会显示UI,但没有来自后端的数据,即浏览器无法理解http://purser.default.svc.cluster.local:3030

【问题讨论】:

  • 我希望你不要试图在没有中间件的情况下直接连接前端和后端。
  • 是的,我们正在使用。你可以在这里查看:github.com/vmware/purser/blob/master/cmd/controller/api/api.go
  • 如果没有 nginx,如果我们将它们都放在同一个 pod 中,一切正常,即都可以使用 localhost 访问

标签: angular nginx kubernetes nginx-reverse-proxy nginx-config


【解决方案1】:

@Kaladin 你的方法差不多了,但我认为缺少一些东西。

我做的是

upstream gateway {
  server gateway-cip-service:3000;
}

server {
  listen 80;

  location /api {
    rewrite /api/(.*) /$1 break;
    proxy_pass http://gateway;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }

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

最头疼的是发现代理头升级,好痛苦。

考虑到我的后端路由没有“api”前缀,这就是我使用“rewrite /api/(.*) /$1 break;”的原因只取 /api/ 之后的任何内容,否则,您可以避免该行代码。

【讨论】:

    【解决方案2】:

    用这个nginx.conf解决了它

    upstream purser {
      server purser.default.svc.cluster.local:3030;
    }
    
    server {
      listen 4200;
    
      location /api {
        proxy_pass http://purser;
      }
    
      location / {
        root /usr/share/nginx/html/purser;
        index index.html index.htm;
        try_files $uri $uri/ /index.html =404;
      }
    } 
    

    并使用BACKEND_URL = window.location.protocol + '//' + window.location.host + '/api/'从前端调用后端

    解释: 前端需要来自后端的数据时在路径/api调用自己,nginx找到这个路径并根据配置将其转发到后端kubernetes服务purser.default.svc.cluster.local:3030使用proxy_pass

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 2021-02-10
      • 2021-07-06
      • 1970-01-01
      • 2021-05-19
      • 2018-02-18
      • 1970-01-01
      • 2018-05-16
      相关资源
      最近更新 更多