Kubernetes 提供了多種機制來管理服務發現、負載均衡和容器健康狀態監控。本文將圍繞以下幾個方面展開:
Service 類型:ClusterIP、NodePort、Headless Service、LoadBalancer(MetallB)
Ingress 的實現原理
健康檢查探針:Liveness、Readiness、Startup
一、Service 類型詳解
1. ClusterIP
ClusterIP 是默認的 Service 類型,用于在集群內部暴露服務。外部無法直接訪問。
apiVersion: v1
kind: Service
metadata:name: nginx-service
spec:selector:app: nginxports:- protocol: TCPport: 8000 # Service 端口targetPort: 80 # Pod 端口type: ClusterIP # 可省略,默認即為 ClusterIP
注釋:
port
: Service 對外提供的端口targetPort
: Pod 中容器監聽的端口集群內可通過?
nginx-service:8000
?訪問該服務
2. NodePort
NodePort 會在每個節點上開放一個靜態端口,外部可通過?節點IP:端口
?訪問服務。
apiVersion: v1
kind: Service
metadata:name: nginx-nodeport
spec:selector:app: nginxports:- protocol: TCPport: 80targetPort: 80nodePort: 30080 # 可選,范圍 30000-32767type: NodePort
注釋:
nodePort
: 若不指定,K8s 會自動分配一個端口外部訪問方式:
http://<節點IP>:30080
3. Headless Service
Headless Service 不分配 ClusterIP,直接返回后端 Pod 的 IP 地址列表。適用于需要直接訪問 Pod 的場景(如 StatefulSet)。
apiVersion: v1
kind: Service
metadata:name: nginx-headless
spec:clusterIP: None # 關鍵字段,表示 Headlessselector:app: nginxports:- protocol: TCPport: 80targetPort: 80
注釋:
DNS 查詢該 Service 會返回所有后端 Pod 的 IP
適用于自定義負載均衡或狀態ful服務發現
4. LoadBalancer 與 MetallB
在云環境中,LoadBalancer 類型會自動分配外部負載均衡器。在裸金屬環境中,可使用 MetallB 實現類似功能。
MetallB 支持兩種模式:
Layer2 模式:通過 ARP/NDP 響應將虛擬 IP 映射到某個節點
BGP 模式:通過 BGP 協議向路由器宣告路由,實現負載均衡
apiVersion: v1
kind: Service
metadata:name: nginx-lb
spec:selector:app: nginxports:- protocol: TCPport: 80targetPort: 80type: LoadBalancer
注釋:
在支持 LoadBalancer 的云平臺中,會自動分配外部 IP
在裸金屬環境中需安裝并配置 MetallB
二、Ingress 原理與功能
Ingress 是管理外部訪問集群服務的 API 對象,通常用于 HTTP/HTTPS 路由。
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:name: example-ingressannotations:nginx.ingress.kubernetes.io/rewrite-target: /
spec:rules:- host: example.comhttp:paths:- path: /apipathType: Prefixbackend:service:name: api-serviceport:number: 80
注釋:
host
: 域名規則path
: 路徑匹配規則backend
: 轉發到的 Service
Ingress 需配合 Ingress Controller(如 nginx-ingress、traefik)使用。
三、健康檢查探針
Kubernetes 提供三種探針來監控容器健康狀態:
1. Liveness Probe(存活探針)
用于檢測容器是否存活,失敗則會重啟容器。
livenessProbe:httpGet:path: /healthport: 8080initialDelaySeconds: 10 # 容器啟動后等待10秒開始檢測periodSeconds: 5 # 每5秒檢測一次
適用場景:檢測死鎖、應用無響應等。
2. Readiness Probe(就緒探針)
用于檢測容器是否準備好接收流量,失敗則從 Service 后端列表中移除。
readinessProbe:exec:command:- cat- /tmp/healthyinitialDelaySeconds: 5periodSeconds: 5
適用場景:等待依賴服務啟動、加載配置完成等。
3. Startup Probe(啟動探針)
用于保護慢啟動容器,避免在啟動過程中被誤殺。
startupProbe:httpGet:path: /startupport: 8080failureThreshold: 30 # 最多嘗試30次periodSeconds: 10 # 每10秒嘗試一次
適用場景:啟動時間較長的 Java 應用、數據庫初始化等。
總結
Kubernetes 通過 Service 和 Ingress 提供了靈活的服務暴露方式,通過健康檢查探針保障了應用的可靠性。合理使用這些機制,可以構建出高可用、易維護的云原生應用。
探針類型 | 作用 | 失敗行為 |
---|---|---|
LivenessProbe | 檢測容器是否存活 | 重啟容器 |
ReadinessProbe | 檢測容器是否就緒 | 從 Service 中移除 |
StartupProbe | 保護慢啟動容器 | 不觸發其他探針 |
建議根據應用特性合理配置探針,避免誤判和頻繁重啟。