我在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
使用此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@@ Kaladin,您的方法几乎在那里,但我认为这里缺少一些东西。