HPA
在kubernetes
集群中被设计成一个controller
,我们可以简单的通过kubectl autoscale
命令来创建一个HPA
资源对象,HPA Controller
默认30s轮询一次(可通过kube-controller-manager
的标志--horizontal-pod-autoscaler-sync-period
进行设置),查询指定的资源(RC或者Deployment)中Pod
的资源使用率,并且与创建时设定的值和指标做对比,从而实现自动伸缩的功能。
1、首先创建一个nginx的pod
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: hpa-nginx-deploy
labels:
app: nginx-demo
spec:
revisionHistoryLimit: 15
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
可以使用kubectl autoscale
命令来创建:
kubectl autoscale deployment hpa-nginx-deploy --cpu-percent=10 --min=1 --max=10
以上命令创建了一个关联资源 hpa-nginx-deploy 的HPA
,最小的 pod 副本数为1,最大为10。HPA
会根据设定的 cpu使用率(10%)动态的增加或者减少pod数量。
2、除了使用kubectl autoscale
命令来创建外,我们依然可以通过创建YAML
文件的形式来创建HPA
资源对象。如果我们不知道怎么编写的话,可以查看上面命令行创建的HPA
的YAML
文件:
$ kubectl get hpa hpa-nginx-deploy -o yaml
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
creationTimestamp: 2017-06-29T08:04:08Z
name: nginxtest
namespace: default
resourceVersion: "951016361"
selfLink: /apis/autoscaling/v1/namespaces/default/horizontalpodautoscalers/nginxtest
uid: 86febb63-5ca1-11e7-aaef-5254004e79a3
spec:
maxReplicas: 5 //资源最大副本数
minReplicas: 1 //资源最小副本数
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment //需要伸缩的资源类型
name: nginxtest //需要伸缩的资源名称
targetCPUUtilizationPercentage: 50 //触发伸缩的cpu使用率
status:
currentCPUUtilizationPercentage: 48 //当前资源下pod的cpu使用率
currentReplicas: 1 //当前的副本数
desiredReplicas: 2 //期望的副本数
lastScaleTime: 2017-07-03T06:32:19Z
根据上面的YAML
文件就可以自己来创建一个基于YAML
的HPA
描述文件了。