K8s ingress-nginx根据请求目录不同将请求转发到不同应用
1. 起因
有小伙伴做实验想要实现以下需求:
2. 实验
2.1 Dockerfile
先准备Dockerfile
bash
FROM nginx:1.20
ADD index.html /usr/share/nginx/html/index.html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
再准备一个index.html
当app1时就把它改为web1 v1.1.0
当app2时就把它改为web2 v1.2.0
html
nginx wework-web1 v1.1.0
2.2 Deployment和SVC
将镜像分别上传至harbor后,通过yaml分别部署app1和app2
app1:
yaml
kind: Deployment
apiVersion: apps/v1
metadata:
labels:
app: nginx-app1
name: nginx-app1
namespace: test-nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx-app1
template:
metadata:
labels:
app: nginx-app1
spec:
containers:
- name: nginx
image: harbor.panasonic.cn/test-nginx/nginx-web:v1.1.0
imagePullPolicy: Always
ports:
- containerPort: 80
resources:
limits:
cpu: 1
memory: "512Mi"
requests:
cpu: 500m
memory: "512Mi"
---
apiVersion: v1
kind: Service
metadata:
name: nginx-app1-svc
namespace: test-nginx
labels:
app: nginx-app1
spec:
ports:
- name: http
port: 80
protocol: TCP
targetPort: 80
selector:
app: nginx-app1
type: ClusterIP
app2:
app2的nodeport是不需要的,我做其他实验时候用到,和此实验无关
yaml
kind: Deployment
apiVersion: apps/v1
metadata:
labels:
app: nginx-app2
name: nginx-app2
namespace: test-nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx-app2
template:
metadata:
labels:
app: nginx-app2
spec:
containers:
- name: nginx
image: harbor.panasonic.cn/test-nginx/nginx-web:v1.2.0
imagePullPolicy: Always
ports:
- containerPort: 80
resources:
limits:
cpu: 1
memory: "512Mi"
requests:
cpu: 500m
memory: "512Mi"
---
apiVersion: v1
kind: Service
metadata:
name: nginx-app2-svc
namespace: test-nginx
labels:
app: nginx-app2
spec:
ports:
- name: http
port: 80
protocol: TCP
targetPort: 80
nodePort: 30080
selector:
app: nginx-app2
type: 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
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: nginx-app1-ing
namespace: test-nginx
# 以下两行是必须的,小伙伴就卡在这里一直报404错误
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: www.pana.com
http:
paths:
- pathType: Prefix
path: /app1
backend:
service:
name: nginx-app1-svc
port:
number: 80
- pathType: Prefix
path: /app2
backend:
service:
name: nginx-app2-svc
port:
number: 80
3. 效果
效果如下
可以看到,我们已经实现了预期的效果
小伙伴试验后也表示明白了