K8s ingress-nginx根据请求目录不同将请求转发到不同应用
1. 起因
有小伙伴做实验想要实现以下需求:
输入www.pana.com/app1访问app1的svc
输入www.pana.com/app2访问app2的svc
2. 实验
2.1 Dockerfile
先准备Dockerfile
FROM nginx:1.20ADD index.html /usr/share/nginx/html/index.htmlEXPOSE 80CMD ["nginx", "-g", "daemon off;"]
再准备一个index.html
当app1时就把它改为web1 v1.1.0
当app2时就把它改为web2 v1.2.0
nginx wework-web1 v1.1.0
2.2 Deployment和SVC
将镜像分别上传至harbor后,通过yaml分别部署app1和app2
app1:
kind: Deployment
apiVersion: apps/v1
metadata:labels:app: nginx-app1name: nginx-app1namespace: test-nginx
spec:replicas: 1selector:matchLabels:app: nginx-app1template:metadata:labels:app: nginx-app1spec:containers:- name: nginximage: harbor.panasonic.cn/test-nginx/nginx-web:v1.1.0imagePullPolicy: Alwaysports:- containerPort: 80resources:limits:cpu: 1memory: "512Mi"requests:cpu: 500mmemory: "512Mi"
---
apiVersion: v1
kind: Service
metadata:name: nginx-app1-svcnamespace: test-nginxlabels:app: nginx-app1
spec:ports:- name: httpport: 80protocol: TCPtargetPort: 80selector:app: nginx-app1type: ClusterIP
app2:
app2的nodeport是不需要的,我做其他实验时候用到,和此实验无关
kind: Deployment
apiVersion: apps/v1
metadata:labels:app: nginx-app2name: nginx-app2namespace: test-nginx
spec:replicas: 1selector:matchLabels:app: nginx-app2template:metadata:labels:app: nginx-app2spec:containers:- name: nginximage: harbor.panasonic.cn/test-nginx/nginx-web:v1.2.0imagePullPolicy: Alwaysports:- containerPort: 80resources:limits:cpu: 1memory: "512Mi"requests:cpu: 500mmemory: "512Mi"
---
apiVersion: v1
kind: Service
metadata:name: nginx-app2-svcnamespace: test-nginxlabels:app: nginx-app2
spec:ports:- name: httpport: 80protocol: TCPtargetPort: 80nodePort: 30080selector:app: nginx-app2type: NodePort
测试是否可以正常访问2个应用
2.3 Ingress
创建Ingress的yaml
注意的是小伙伴因为看了之前另外个tomcat的文档发现安装那个配置就一直404报错.
原因也很简单,另外个实验的目录是放在不通的uri下:
app1: www.pana.com/app1
app2: www.pana.com/app2
那么就不需要再对地址重写,而我们这里2个index都是在/下面
那么在匹配了path后就需要将它重写到app的/,于是就用到了nginx.ingress.kubernetes.io/rewrite-target
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:name: nginx-app1-ingnamespace: test-nginx# 以下两行是必须的,小伙伴就卡在这里一直报404错误annotations:nginx.ingress.kubernetes.io/rewrite-target: /
spec:ingressClassName: nginxrules:- host: www.pana.comhttp:paths:- pathType: Prefixpath: /app1backend:service:name: nginx-app1-svcport:number: 80- pathType: Prefixpath: /app2backend:service:name: nginx-app2-svcport:number: 80
3. 效果
效果如下
可以看到,我们已经实现了预期的效果
小伙伴试验后也表示明白了