k8s從入門到放棄之Service負載均衡
在 Kubernetes (K8s) 中,Service 是一種抽象,它定義了一組邏輯上的 Pod 和訪問它們的策略。Service 的主要目的是提供一種可靠的方式來訪問一組具有相同標簽(Label)的 Pod,即使這些 Pod 可能會在集群中被動態地創建或銷毀。
Service的核心功能
- 服務發現:通過 DNS 或者環境變量的方式,讓其他應用可以找到并訪問到這個 Service。
- 負載均衡:將到達 Service 的請求分發給后端的多個 Pod 實例。
- 穩定的 IP 地址和 DNS 名稱:為一組 Pod 提供一個固定的 IP 地址和 DNS 名稱,即使后端的 Pod 發生了變化,如重啟、擴展等操作。
- 流量代理:通過 kube-proxy 組件實現對流量的轉發,支持多種代理模式,包括 userspace、iptables 和 IPVS。
Service的類型
- ClusterIP:默認類型,通過集群內部 IP 暴露服務,只能從集群內部訪問。
- NodePort:通過每個節點的 IP 和靜態端口暴露服務,允許外部流量通過節點 IP 和 NodePort 訪問服務。
- LoadBalancer:通常用于云環境中,自動創建一個外部負載均衡器,并分配一個外部 IP 來暴露服務。
ClusterIP案例
資源文檔kubectl explain Service.spec
apiVersion: apps/v1
kind: Deployment
metadata:name: deploy-nginx
spec:replicas: 1strategy:type: Recreateselector:matchLabels:app: webtemplate:metadata:labels:app: webspec:containers:- name: nginximage: nginx:1.20.0readinessProbe:tcpSocket:port: 80resources:limits:cpu: "100m"ports:- containerPort: 80
---apiVersion: v1
kind: Service
metadata:name: nginx-svc
spec:type: ClusterIPselector:app: webports:- protocol: TCPport: 80targetPort: 80
NodePort案例
資源文檔kubectl explain Service.spec
apiVersion: apps/v1
kind: Deployment
metadata:name: deploy-nginx
spec:replicas: 1strategy:type: Recreateselector:matchLabels:app: webtemplate:metadata:labels:app: webspec:containers:- name: nginximage: nginx:1.20.0readinessProbe:tcpSocket:port: 80resources:limits:cpu: "100m"ports:- containerPort: 80---apiVersion: v1
kind: Service
metadata:name: nginx-svc
spec:type: NodePortselector:app: webports:- protocol: TCPport: 80targetPort: 80
查看集群外部訪問地址
[root@master /]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 20d
nginx-svc NodePort 10.107.140.239 <none> 80:32017/TCP 2m16s
LoadBalancer案例
資源文檔 kubectl explain Service.spec
apiVersion: apps/v1
kind: Deployment
metadata:name: deploy-nginx
spec:replicas: 1strategy:type: Recreateselector:matchLabels:app: webtemplate:metadata:labels:app: webspec:containers:- name: nginximage: nginx:1.20.0readinessProbe:tcpSocket:port: 80resources:limits:cpu: "100m"ports:- containerPort: 80---apiVersion: v1
kind: Service
metadata:name: nginx-svc
spec:type: LoadBalancerselector:app: webports:- protocol: TCPport: 80targetPort: 80
查看集群外部訪問地址
[root@master /]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 20d
nginx-svc LoadBalancer 10.101.116.99 10.244.2.240 80:30143/TCP 2m40s
Service 是 Kubernetes 中非常重要的概念之一,它使得應用程序可以在分布式系統中進行有效的通信和協作。通過合理配置 Service,可以確保應用即使在高動態性的容器化環境中也能保持良好的可用性和可訪問性。