如何在Kubernetes中使用ngnix连接后端与前端

问题描述 投票:2回答:2

我在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:当我们点击ui服务时,在proxy_pass中设置了nginx.conf时,它重定向到后端并直接从后端提供json输出。

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

enter image description here

angular nginx kubernetes nginx-reverse-proxy nginx-config
2个回答
3
投票

使用此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会找到此路径,并根据配置使用purser.default.svc.cluster.local:3030]将其转发到后端kubernetes服务[C0

0
投票

@@ Kaladin,您的方法几乎在那里,但我认为这里缺少一些东西。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.