上一篇学习笔记中,我们了解并应用了k8s的calico网络插件。本章将在其基础上通过Ingress-nginx实现k8s的七层负载均衡。相比较之前的四层负载均衡会多一些重定向、反向代理等功能。
Ingress是一个API对象,和其他对象一样,通过yaml文件来配置。ingress通过http或https暴露集群内部service,给service提供外部URL、负载均衡、SSL/TLS能力以及基于host的方向代理。
镜像准备:
,harbor仓库中新建项目ingress-nginx,压入镜像到harbor仓库
docker tag reg.westos.org/ingress-nginx/controller:v0.48.1 hyl.westos.org/ingress-nginx/controller:v0.48.1
docker tag reg.westos.org/ingress-nginx/kube-webhook-certgen:v1.5.1 hyl.westos.org/ingress-nginx/kube-webhook-certgen:v1.5.1
docker push hyl.westos.org/ingress-nginx/controller:v0.48.1
docker push hyl.westos.org/ingress-nginx/kube-webhook-certgen:v1.5.1
进入仓库查看镜像是否上传成功
官网下载ingress-nginx部署所需资源清单,修改镜像get地址为本地harbor仓库。
拉起pod节点,kubectl apply -f deploy.yaml
kubectl get ns
查看ingress-nginx的所有信息,可以看到ingress-nginx-controller已经running
kubectl -n ingress-nginx get all
kubectl -n ingress-nginx get svc
添加svc服务
vim svc.yaml
apiVersion: v1
kind: Service
metadata:
name: mysvc
spec:
ports:
- protocol: TCP
port: 80
targetPort: 80
selector:
app: myapp
拉起服务并查看endpoint
修改svc配置文件为负载均衡
kubectl -n ingress-nginx edit svc ingress-nginx-controller
查看修改内容
kubectl -n ingress-nginx get svc
可以通过此方式动态分配IP,而不是占用主机资源
修改deployment标签,为重定向作准备,给定不同版本的镜像,方便看到反向代理的结果差异。之前标签myapp的版本是v1 这里是版本v2
vim deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: myapp:v2
拉起deployment,通过标签来锁定域名
为标签为nginx的deployment添加服务
vim nginx-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-svc
spec:
ports:
- protocol: TCP
port: 80
targetPort: 80
selector:
app: nginx
修改标签为myapp的svc名称,方便对比
重新拉起两个svc
kubectl apply -f nginx-svc.yaml
kubectl apply -f myapp-svc.yaml
kubectl describe svc myapp-svc
kubectl describe svc nginx-svc
配置服务与ingress连接,并给定域名
vim ingress.yaml
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: ingress-nginx
spec:
rules:
- host: www1.westos.org
http:
paths:
- path: /
backend:
serviceName: nginx-svc
servicePort: 80
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: ingress-myapp
spec:
rules:
- host: www2.westos.org
http:
paths:
- path: /
backend:
serviceName: myapp-svc
servicePort: 80
拉起资源清单
kubectl apply -f ingress.yaml
kubectl get ingress
测试:
测试机添加解析到服务节点172.25.9.10
访问测试:
curl www1.westos.org
curl www2.westos.org