什么是HPA?
The Horizontal Pod Autoscaler automatically scales the number of pods in a replication controller, deployment or replica set based on observed CPU utilization (or, with custom metrics support, on some other application-provided metrics). Note that Horizontal Pod Autoscaling does not apply to objects that can’t be scaled, for example, DaemonSets.
Horizontal Pod Autoscaler根據(jù)觀察到的CPU利用率自動調(diào)整復制控制器,部署或副本集中的容器數(shù)量(或者,通過自定義指標支持,根據(jù)其他一些應(yīng)用程序提供的指標)。 請注意,Horizontal Pod Autoscaling不適用于無法縮放的對象,例如DaemonSet。
The Horizontal Pod Autoscaler is implemented as a Kubernetes API resource and a controller. The resource determines the behavior of the controller. The controller periodically adjusts the number of replicas in a replication controller or deployment to match the observed average CPU utilization to the target specified by user.
Horizontal Pod Autoscaler實現(xiàn)為Kubernetes API資源和控制器。 資源確定控制器的行為。 控制器會定期調(diào)整復制控制器或部署中的副本數(shù),以使觀察到的平均CPU利用率與用戶指定的目標相匹配。
Horizontal Pod Autoscaling僅適用于Deployment和ReplicaSet,在V1版本中僅支持根據(jù)Pod的CPU利用率擴所容,在v1alpha版本中,支持根據(jù)內(nèi)存和用戶自定義的metric擴縮容。
提問:
1. Deployment, Replication controller, ReplicaSet的區(qū)別?
2. 為什么DaemonSet不支持?

為什么HPA
應(yīng)用的資源使用率通常都有高峰和低谷的時候,如何削峰填谷,提高集群的整體資源利用率,讓service中的Pod個數(shù)自動調(diào)整呢?這就有賴于Horizontal Pod Autoscaling了,顧名思義,使Pod水平自動縮放。這個Object(跟Pod、Deployment一樣都是API resource)也是最能體現(xiàn)kubernetes之于傳統(tǒng)運維價值的地方,不再需要手動擴容了,終于實現(xiàn)自動化了,還可以自定義指標,沒準未來還可以通過人工智能自動進化呢!例如聯(lián)動Prometheus實現(xiàn)預測告警和預測伸縮。
Metrics支持
在不同版本的API中,HPA autoscale時可以根據(jù)以下指標來判斷:
autoscaling/v1
CPU
autoscaling/v1alpha1
內(nèi)存
自定義metrics
kubernetes1.6起支持自定義metrics,但是必須在kube-controller-manager中配置如下兩項:
--horizontal-pod-autoscaler-use-rest-clients=true
--api-server指向kube-aggregator,也可以使用heapster來實現(xiàn),通過在啟動heapster的時候指定--api-server=true。查看kubernetes metrics
多種metrics組合
HPA會根據(jù)每個metric的值計算出scale的值,并將最大的那個值作為擴容的最終結(jié)果。
演示根據(jù)CPU進行伸縮
1. 創(chuàng)建一個部署Deployment并把它通過服務(wù)暴露出來
kubectl run php-apache --image=k8s.gcr.io/hpa-example --requests=cpu=200m --expose --port=80
2. 創(chuàng)建HPA
kubectl autoscale deployment php-apache --cpu-percent=50--min=1--max=10?
3. 檢查HPA狀態(tài)
kubectl get hpa
4. 加壓
kubectl run -i --tty load-generator --image=busybox /bin/sh
whiletrue;dowget -q -O- http://php-apache.default.svc.cluster.local;done
5. 過1分鐘左右再次檢查HPA狀態(tài)和部署狀態(tài)
kubectl get hpa
kubectl get deployment php-apache
6. 停壓,等1分鐘查看狀態(tài)
演示根據(jù)自定義指標http_requests實現(xiàn)伸縮
參考: