K8S原来如此简单(五)Metrics Server与HPA

什么是HPA

https://kubernetes.io/zh/docs/tasks/run-application/horizontal-pod-autoscale/

 我们前面有通过kubectl scale命令手动扩展我们的服务,生产环境中我们希望k8s能够根据一些指标信息自动扩展服务。

这时我们可以利用k8s的HPA(水平扩展)来根据 CPU利用率等指标自动扩缩Deployment、ReplicaSet 或 StatefulSet 中的 Pod 数量。

HPA原理

HPA控制器通过Metrics Server的API(Heapster的API或聚合API)获取指标数据,基于用户定义的扩缩容规则进行计算,得到目标Pod副本数量。

当目标Pod副本数量与 当前副本数量不同时,HPA控制器就向Pod的副本控制器 (Deployment、RC或ReplicaSet)发起scale操作,调整Pod的副本数量, 完成扩缩容操作。

MetricsServer

在说metricsserver之前,我们来看一个查看资源消耗情况的命令

查看Node资源消耗:
kubectl top node k8s-node1
查看Pod资源消耗:
kubectl top pod k8s-node1

需要注意的是,使用这个命令我们需要安装metrics server,否则会提示:Metrics API不可用。

安装metrics server

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

查看metrics安装结果

kubectl get pod –all-namespaces |grep metrics

查看pod资源使用率

kubectl top pod chesterdeployment-75c64cc8b6-k4jqw -n chesterns

安装好之后,我们可以看到已经可以正常使用kubectl top命令了。下面我们开始演示通过hpa来模拟根据cpu自动水平扩展。

仍然使用之前课程的deployment,需要修改deployment的副本数为1

apiVersion: apps/v1
kind: Deployment
metadata:
name: chesterdeployment
namespace: chesterns
labels:
app: chesterapi
spec:
replicas: 1
selector:
matchLabels:
app: chesterapi
template:
metadata:
labels:
app: chesterapi
spec:
containers:
- name: oneapi
image: registry.cn-beijing.aliyuncs.com/chester-k8s/oneapi:latest
ports:
- containerPort: 5000
livenessProbe:
httpGet:
path: /test
port: 5000

应用deployment

kubectl apply -f deployment.yaml

在我们的oneapi里有一个highcpu的接口,可以帮助我们实现高cpu操作

\[HttpGet("highcpu")\]
public string HighCpu(int minutes)
{
    var now = DateTime.Now;
    while (DateTime.Now - now <= TimeSpan.FromMinutes(minutes))
    {
        \_logger.LogInformation(DateTime.Now.ToString());
    }
    return "ok";
}

我们调用这个接口,模拟高消耗cpu操作

curl clusterip:5000/test/highcpu?minutes=1

再次查看pod资源使用率,可以跟调用之前比对,明显发现cpu变高

kubectl top pod chesterdeployment-75c64cc8b6-k4jqw -n chesterns

创建HPA

下面我们创建hpa,让其实现自动扩展

apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
name: chesterhpa
namespace: chesterns
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: chesterdeployment
minReplicas: 1
maxReplicas: 3
metrics:
- type: Resource
resource:
name: cpu
target:
type: AverageValue
averageValue: 200m

重新调用接口模拟高cpu

curl clusterip:5000/test/highcpu?minutes=3

查看hpa状态,即可发现实现了自动扩展

kubectl describe hpa chesterhpa -n chesterns
kubectl get pods –namespace=chesterns
kubectl top pod -n chesterns​