本文演示如何在 K8s 集群中使用 Ingress Nginx 的功能,完成对应用内容的路由。
应用的构建请参考 在 k8s 集群中发布 SpringBoot 应用,在该文章中,我们使用NodePort方式暴露端口,在本文中,我们演示使用 Ingress 暴露端口
部署 Ingress Controller
下载官方安装文件
1
| git clone https://github.com/nginxinc/kubernetes-ingress.git
|
进入 kubernetes-ingress/deployments 目录
创建Namespace和ServiceAccount
1
| kubectl apply -f common/ns-and-sa.yaml
|
创建Secrets自签名证书,
1
| kubectl apply -f common/default-server-secret.yaml
|
创建ConfigMap自定义配置文件
1
| kubectl apply -f common/nginx-config.yaml
|
配置RBAC认证授权,实现ingress控制器访问集群中的其他资源
1
| kubectl apply -f rbac/rbac.yaml
|
1
| kubectl apply -f common/ingress-class.yaml
|
进入 common/crds 目录
1
| kubectl apply -f k8s.nginx.org_globalconfigurations.yaml
|
1
| kubectl apply -f k8s.nginx.org_policies.yaml
|
1
| kubectl apply -f k8s.nginx.org_transportservers.yaml
|
1
| kubectl apply -f k8s.nginx.org_virtualserverroutes.yaml
|
1
| kubectl apply -f k8s.nginx.org_virtualservers.yaml
|
DaemonSets的方式部署控制器
修改 daemon-set/nginx-ingress.yaml, 将 80 修改为 18090, 443 修改为 18443
1 2 3 4 5 6
| - name: http containerPort: 80 hostPort: 31090 - name: https containerPort: 443 hostPort: 31443
|
1
| kubectl apply -f daemon-set/nginx-ingress.yaml
|
检查部署情况
1
| kubectl get daemonsets -n nginx-ingress
|
1 2
| NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE nginx-ingress 2 2 2 2 2 <none> 4m22s
|
1
| kubectl get pods -n nginx-ingress -o wide
|
1 2 3
| NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES nginx-ingress-26z6g 1/1 Running 0 5m15s 10.244.1.22 node-03 <none> <none> nginx-ingress-qf7rf 1/1 Running 0 5m15s 10.244.2.12 node-02 <none> <none>
|
现在,就可以通过内网地址访问两个工作节点上的 Nginx 服务,查看是否正常,比如
1
| curl http://192.168.11.2:31090
|
如果正常,可以看到 nginx 的输出
1 2 3 4 5 6 7
| <html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.21.3</center> </body> </html>
|
部署一个测试的 Nginx
首先,需要部署 api-ok 服务。
api-srv.yaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| apiVersion: v1 kind: Service metadata: name: api-ok-srv namespace: default labels: app: api-ok-srv spec: type: NodePort ports: - port: 8080 nodePort: 31199 selector: app: api-ok-srv-deployment --- apiVersion: apps/v1 kind: Deployment metadata: name: api-ok-srv-deployment labels: app: api-ok-srv-deployment spec: replicas: 1 selector: matchLabels: app: api-ok-srv-deployment template: metadata: labels: app: api-ok-srv-deployment spec: imagePullSecrets: - name: my-registry-secret containers: - name: api-ok-srv-deployment image: 192.168.0.104:5000/api-ok-srv:latest
|
建立 Nginx 路由规则
ok-api.yaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ok-ingress spec: ingressClassName: nginx rules: - host: api.example.com http: paths: - path: / pathType: Prefix backend: service: name: api-ok-srv port: number: 8080
|
访问
1
| http://api.example.com:31090/ok
|