【Kubernetes】HPA学习笔记-样例demo

环境准备

HPA依赖监控服务,默认监控使用metris-server,因此先要部署metrics-server

一、创建Deployment和Service

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ngx-dep

spec:
  replicas: 1
  selector:
    matchLabels:
      app: ngx-dep

  template:
    metadata:
      labels:
        app: ngx-dep
    spec:
      containers:
      - image: nginx:alpine
        name: nginx
        ports:
        - containerPort: 80

        resources:
          requests:
            cpu: 50m
            memory: 10Mi
          limits:
            cpu: 100m
            memory: 20Mi
---

apiVersion: v1
kind: Service
metadata:
  name: ngx-svc
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: ngx-dep

二、创建HPA

targetCPUUtilizationPercentage: 所有podCPU负载之和/所有pod CPU requests之和
pod自动扩容至平均每个pod负载低于targetCPUUtilizationPercentage。

公式:期望副本数 = ceil[当前副本数 * (当前指标 / 期望指标)]
例如,如果当前指标值为 200m,而期望值为 100m,则副本数将加倍, 因为 200.0 / 100.0 == 2.0 如果当前值为 50m,则副本数将减半, 因为 50.0 / 100.0 == 0.5。如果比率足够接近 1.0(在全局可配置的容差范围内,默认为 0.1), 则控制平面会跳过扩缩操作。

autoscaling提供了两个版本,v2拓展了支持的metrics类型,可以使用Prometheus等系统提供的metrics,详见官方文档:Pod水平自动扩缩

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: ngx-hpa

spec:
  maxReplicas: 10
  minReplicas: 2
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: ngx-dep
  targetCPUUtilizationPercentage: 100

v2 API如下:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: ngx-hpa

spec:
  maxReplicas: 10
  minReplicas: 2
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: ngx-dep
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 100

三、测试

## 使用hpptd提供的apache benchmark
kubectl run test -it --image=httpd:alpine -- sh
## 发送100w个请求
ab -c 10 -t 60 -n 1000000 'http://ngx-svc/'

结果:
可以观察到期初pod为1个,检测到pod指标后自动扩容到最小pod数2个,随后随着压力增大,知道扩容至9个,在流量高峰过后,逐步缩容至2个。
在这里插入图片描述

四、常用观察指令

kubectl apply -f ngx-dep.yaml
kubectl apply -f ngx-hpa.yaml
watch -n 1 "kubectl top pod"
kubectl get hpa -w
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值