在 Kubernetes 中,HorizontalPodAutoscaler 自動更新工作負載資源 (例如 Deployment 或者 StatefulSet), 目的是自動擴縮工作負載以滿足需求。
hpa的使用本身還是很簡單的
示例如下:
官網示例
apiVersion: apps/v1
kind: Deployment
metadata:name: php-apache
spec:selector:matchLabels:run: php-apachetemplate:metadata:labels:run: php-apachespec:containers:- name: php-apacheimage: registry.k8s.io/hpa-exampleports:- containerPort: 80resources:limits:cpu: 500mrequests:cpu: 200m
---
apiVersion: v1
kind: Service
metadata:name: php-apachelabels:run: php-apache
spec:ports:- port: 80selector:run: php-apache
kubectl apply -f https://k8s.io/examples/application/php-apache.yaml
運行起來后,
kubectl autoscale deployment php-apache --cpu-percent=50 --min=1 --max=10
–cpu-percent就是cpu使用率指標,超過就會自動擴容副本,更加詳細的說明看官網對這里的算法解釋
**官網說明**
增加負載去測試驗證:
kubectl run -i --tty load-generator --rm --image=busybox:1.28 --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done"
觀察:
kubectl get hpa php-apache --watch
停止負載后,pod會伸縮回來