什么是HPA
https://kubernetes.io/zh/docs/tasks/run-application/horizontal-pod-autoscale/
我們前面有通過kubectl scale命令手動擴展我們的服務,生產環境中我們希望k8s能夠根據一些指標資訊自動擴展服務,
這時我們可以利用k8s的HPA(水平擴展)來根據 CPU利用率等指標自動擴縮Deployment、ReplicaSet 或 StatefulSet 中的 Pod 數量,
HPA原理
HPA控制器通過Metrics Server的API(Heapster的API或聚合API)獲取指標資料,基于用戶定義的擴縮容規則進行計算,得到目標Pod副本數量,
當目標Pod副本數量與 當前副本數量不同時,HPA控制器就向Pod的副本控制器 (Deployment、RC或ReplicaSet)發起scale操作,調整Pod的副本數量, 完成擴縮容操作,

MetricsServer
在說metricsserver之前,我們來看一個查看資源消耗情況的命令
查看Node資源消耗: kubectl top node k8s-node1 查看Pod資源消耗: kubectl top pod k8s-node1
需要注意的是,使用這個命令我們需要安裝metrics server,否則會提示:Metrics API不可用,
安裝metrics server
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
查看metrics安裝結果
kubectl get pod --all-namespaces |grep metrics
查看pod資源使用率
kubectl top pod chesterdeployment-75c64cc8b6-k4jqw -n chesterns
安裝好之后,我們可以看到已經可以正常使用kubectl top命令了,下面我們開始演示通過hpa來模擬根據cpu自動水平擴展,
仍然使用之前課程的deployment,需要修改deployment的副本數為1
apiVersion: apps/v1 kind: Deployment metadata: name: chesterdeployment namespace: chesterns labels: app: chesterapi spec: replicas: 1 selector: matchLabels: app: chesterapi template: metadata: labels: app: chesterapi spec: containers: - name: oneapi image: registry.cn-beijing.aliyuncs.com/chester-k8s/oneapi:latest ports: - containerPort: 5000 livenessProbe: httpGet: path: /test port: 5000
應用deployment
kubectl apply -f deployment.yaml
在我們的oneapi里有一個highcpu的介面,可以幫助我們實作高cpu操作
[HttpGet("highcpu")] public string HighCpu(int minutes) { var now = DateTime.Now; while (DateTime.Now - now <= TimeSpan.FromMinutes(minutes)) { _logger.LogInformation(DateTime.Now.ToString()); } return "ok"; }
我們呼叫這個介面,模擬高消耗cpu操作
curl clusterip:5000/test/highcpu?minutes=1
再次查看pod資源使用率,可以跟呼叫之前比對,明顯發現cpu變高
kubectl top pod chesterdeployment-75c64cc8b6-k4jqw -n chesterns
創建HPA
下面我們創建hpa,讓其實作自動擴展
apiVersion: autoscaling/v2beta2 kind: HorizontalPodAutoscaler metadata: name: chesterhpa namespace: chesterns spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: chesterdeployment minReplicas: 1 maxReplicas: 3 metrics: - type: Resource resource: name: cpu target: type: AverageValue averageValue: 200m
重新呼叫介面模擬高cpu
curl clusterip:5000/test/highcpu?minutes=3
查看hpa狀態,即可發現實作了自動擴展
kubectl describe hpa chesterhpa -n chesterns kubectl get pods --namespace=chesterns kubectl top pod -n chesterns?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/449083.html
標籤:其他
上一篇:搭建Hyperledger Fabric 2.3.2開發環境及簡單案例運行
下一篇:機器學習里的資訊論
