导语:在k8s中通过nginx部署前端 发布后遇到无法访问和启动失败的问题

  1. 要求api-server-svc这个service要先创建,否则nginx启动时会因为无法解析api-server-svc而启动失败
  2. nginx服役期间,如果后端服务重启,svc ip改变了,代理会失败,因为nginx缓存了旧ip
  # dns设置缓存时间5s,解决问题2
  resolver kube-dns.kube-system.svc.cluster.local valid=5s;
  # 使用变量方式,解决后端还未启动时前端nginx会报错
  set $apiserver api-server-svc.对应namespace.svc.cluster.local;  


            location /api {
                proxy_set_header   X-Forwarded-Proto $scheme;
                proxy_set_header   Host              $http_host;
                proxy_set_header   X-Real-IP         $remote_addr;
                rewrite /api/(.*) /$1 break;
                proxy_pass http://$apiserver:8080;
            }


            location /aiconsole/ {
                proxy_set_header Host $host;
                proxy_set_header X-Real-Ip $remote_addr;
                proxy_set_header REMOTE-HOST $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                # 代理后端真实地址
                proxy_pass http://platform:11380/aiconsole/;
            }

至于namespace的获取 可以通过添加脚本来实现。

#!/usr/bin/env bash

echo "################################## Run nginx"
export DOLLAR='$'
envsubst '${SVRSHELL_PORT}' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf # /etc/nginx/conf.d/default.conf

NS=`cat /var/run/secrets/kubernetes.io/serviceaccount/namespace`
sed -i  's/namespace/$NS/g' /etc/nginx/conf.d/default.conf


echo "Generate nginx.conf"
cat /etc/nginx/conf.d/default.conf
echo "################################## Start server"
nginx -g "daemon off;"

参考

https://blog.csdn.net/u010837612/article/details/123275026

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐