Ingress 統一訪問入口
什麼是 Ingress
通常情況下,Service 和 Pod 的 IP 僅可在集羣內部訪問。集羣外部的請求需要通過負載均衡轉發到 Service 在 Node 上暴露的 NodePort 上,然後再由 kube-proxy 通過邊緣路由器 (edge router) 將其轉發給相關的 Pod 或者丟棄。而 Ingress 就是爲進入集羣的請求提供路由規則的集合
Ingress 可以給 Service 提供集羣外部訪問的 URL、負載均衡、SSL 終止、HTTP 路由等。爲了配置這些 Ingress 規則,集羣管理員需要部署一個 Ingress Controller,它監聽 Ingress 和 Service 的變化,並根據規則配置負載均衡並提供訪問入口。
使用 Nginx Ingress Controller
本次實踐的主要目的就是將入口統一,不再通過 LoadBalancer 等方式將端口暴露出來,而是使用 Ingress 提供的反向代理負載均衡功能作爲我們的唯一入口。通過以下步驟操作仔細體會。
注意: 下面包含資源配置的步驟都是自行創建 YAML 配置文件通過
kubectl create -f
和kubectl delete -f
部署和刪除
部署 Tomcat
部署 Tomcat 但僅允許在內網訪問,我們要通過 Ingress 提供的反向代理功能路由到 Tomcat 之上
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: tomcat-app
spec:
replicas: 1
template:
metadata:
labels:
name: tomcat
spec:
containers:
- name: tomcat
image: tomcat
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: tomcat-http
spec:
ports:
- port: 8080
targetPort: 8080
# ClusterIP, NodePort, LoadBalancer
type: ClusterIP
selector:
name: tomcat
部署
kubectl apply -f tomcat.yml
安裝 Nginx Ingress Controller
Ingress Controller 有許多種,我們選擇最熟悉的 Nginx 來處理請求,其它可以參考 官方文檔
創建一個ingress文件夾
mkdir -p /usr/local/k8s/ingress && cd /usr/local/k8s/ingress
下載 Nginx Ingress Controller 配置文件
wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/static/mandatory.yaml
修改配置文件,找到配置如下位置 在下面增加一句 hostNetwork: true
vim mandatory.yaml
安裝
kubectl apply -f mandatory.yaml
部署 Ingress
新建一個ingress-deployment.yml
vim ingress-deployment.yml
內容如下
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: nginx-web
annotations:
# 指定 Ingress Controller 的類型
kubernetes.io/ingress.class: "nginx"
# 指定我們的 rules 的 path 可以使用正則表達式
nginx.ingress.kubernetes.io/use-regex: "true"
# 連接超時時間,默認爲 5s
nginx.ingress.kubernetes.io/proxy-connect-timeout: "600"
# 後端服務器迴轉數據超時時間,默認爲 60s
nginx.ingress.kubernetes.io/proxy-send-timeout: "600"
# 後端服務器響應超時時間,默認爲 60s
nginx.ingress.kubernetes.io/proxy-read-timeout: "600"
# 客戶端上傳文件,最大大小,默認爲 20m
nginx.ingress.kubernetes.io/proxy-body-size: "10m"
# URL 重寫
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
# 路由規則
rules:
# 主機名,只能是域名,修改爲你自己的
- host: k8s.test.com
http:
paths:
- path:
backend:
# 後臺部署的 Service Name,與上面部署的 Tomcat 對應
serviceName: tomcat-http
# 後臺部署的 Service Port,與上面部署的 Tomcat 對應
servicePort: 8080
部署
kubectl apply -f ingress-deployment.yml
查看 Nginx Ingress Controller
kubectl get pods -n ingress-nginx -o wide
查看 Ingress
kubectl get ingress