HPAkubernetes集群中被设计成一个controller,我们可以简单的通过kubectl autoscale命令来创建一个HPA资源对象,HPA Controller默认30s轮询一次(可通过kube-controller-manager的标志--horizontal-pod-autoscaler-sync-period进行设置),查询指定的资源(RC或者Deployment)中Pod的资源使用率,并且与创建时设定的值和指标做对比,从而实现自动伸缩的功能。

    1、首先创建一个nginx的pod

    1. ---
    2. apiVersion: apps/v1
    3. kind: Deployment
    4. metadata:
    5. name: hpa-nginx-deploy
    6. labels:
    7. app: nginx-demo
    8. spec:
    9. revisionHistoryLimit: 15
    10. selector:
    11. matchLabels:
    12. app: nginx
    13. template:
    14. metadata:
    15. labels:
    16. app: nginx
    17. spec:
    18. containers:
    19. - name: nginx
    20. image: nginx
    21. ports:
    22. - containerPort: 80

    可以使用kubectl autoscale命令来创建:

    1. 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资源对象。如果我们不知道怎么编写的话,可以查看上面命令行创建的HPAYAML文件:

    1. $ kubectl get hpa hpa-nginx-deploy -o yaml
    2. apiVersion: autoscaling/v1
    3. kind: HorizontalPodAutoscaler
    4. metadata:
    5. creationTimestamp: 2017-06-29T08:04:08Z
    6. name: nginxtest
    7. namespace: default
    8. resourceVersion: "951016361"
    9. selfLink: /apis/autoscaling/v1/namespaces/default/horizontalpodautoscalers/nginxtest
    10. uid: 86febb63-5ca1-11e7-aaef-5254004e79a3
    11. spec:
    12. maxReplicas: 5 //资源最大副本数
    13. minReplicas: 1 //资源最小副本数
    14. scaleTargetRef:
    15. apiVersion: apps/v1
    16. kind: Deployment //需要伸缩的资源类型
    17. name: nginxtest //需要伸缩的资源名称
    18. targetCPUUtilizationPercentage: 50 //触发伸缩的cpu使用率
    19. status:
    20. currentCPUUtilizationPercentage: 48 //当前资源下pod的cpu使用率
    21. currentReplicas: 1 //当前的副本数
    22. desiredReplicas: 2 //期望的副本数
    23. lastScaleTime: 2017-07-03T06:32:19Z

    根据上面的YAML文件就可以自己来创建一个基于YAMLHPA描述文件了。