HPA自动扩缩容

HPA(了解)

HorizontalPodAutoscaler(简称 HPA ) 自动更新工作负载资源(例如 Deployment 或者
StatefulSet), 目的是自动扩缩工作负载以满足需求。
水平扩缩意味着对增加的负载的响应是部署更多的 Pod。 这与“垂直(Vertical)”扩缩不同,对于
Kubernetes, 垂直扩缩意味着将更多资源(例如:内存或 CPU)分配给已经为工作负载运行的 Pod。
如果负载减少,并且 Pod 的数量高于配置的最小值, HorizontalPodAutoscaler 会指示工作负载资源
(Deployment、StatefulSet 或其他类似资源)缩减。
本文档将引导你完成启用 HorizontalPodAutoscaler 以自动管理示例 Web 应用程序的扩缩的示例。 此
示例工作负载是运行一些 PHP 代码的 Apache httpd

# 总结:HPA可根据 系统负载 情况(CPU、MEM、Disk...)对控制器(Deployment、StatefulSet 、
ReplicaSet)进行操作,修改副本(replicas)数量,达到扩缩容的目的

HPA工作流程图

c355ad444b32694958479ae997b0448.jpg

image-20240924143055345



Metrics Server介绍(了解)
Metrics Server是Kubernetes内置自动缩放管道的可扩展、高效的容器资源度量源。
Metrics Server从Kubelets收集资源度量,并通过Metrics API在Kubernetes apiserver中公开这些度
量,供Horizontal Pod Autoscaler和Vertical Pod Autocaler使用。kubectl top还可以访问度量API,从
而更容易地调试自动缩放管道。

工作流程图

image-20240924143055345

版本信息

image-20240924143200436

Metrics Server的部署
# 在master运行
kubectl top node
error: Metrics API not available (报错就下载Metrics Server)
# 下载Metrics Server
wget http://test.driverzeng.com/HPA/metrics-server.tar
# 在所有node节点导入镜像
docker load < metrics-server.tar
#########################################
# ## Metrics Server资源清单
vim components.yaml
piVersion: v1
kind: ServiceAccount
metadata:
  labels:
    k8s-app: metrics-server
  name: metrics-server
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    k8s-app: metrics-server
    rbac.authorization.k8s.io/aggregate-to-admin: "true"
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
    rbac.authorization.k8s.io/aggregate-to-view: "true"
  name: system:aggregated-metrics-reader
rules:
- apiGroups:
  - metrics.k8s.io
  resources:
  - pods
  - nodes
  verbs:
  - get
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    k8s-app: metrics-server
  name: system:metrics-server
rules:
- apiGroups:
  - pods
  - nodes
  - nodes/stats
  - namespaces
  - configmaps
  verbs:
  - get
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  labels:
    k8s-app: metrics-server
  name: metrics-server-auth-reader
  namespace: kube-system
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: extension-apiserver-authentication-reader
subjects:
- kind: ServiceAccount
  name: metrics-server
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    k8s-app: metrics-server
 name: metrics-server:system:auth-delegator
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
- kind: ServiceAccount
  name: metrics-server
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    k8s-app: metrics-server
  name: system:metrics-server
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:metrics-server
subjects:
- kind: ServiceAccount
  name: metrics-server
  namespace: kube-system
---
apiVersion: v1
kind: Service
metadata:
  labels:
    k8s-app: metrics-server
  name: metrics-server
  namespace: kube-system
spec:
  ports:
  - name: https
    port: 443
    protocol: TCP
    targetPort: https
  selector:
    k8s-app: metrics-server
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  labels:
    k8s-app: metrics-server
  name: metrics-server
  namespace: kube-system
spec:
  selector:
    matchLabels:
      k8s-app: metrics-server
  template:
    metadata:
      labels:
        k8s-app: metrics-server
    spec:
      hostNetwork: true
      containers:
      - args:
        - --cert-dir=/tmp
        - --secure-port=4443
        - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
        - --kubelet-use-node-status-port
        - --kubelet-insecure-tls
        image: metrics-server:v0.4.0
        imagePullPolicy: IfNotPresent
       livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /livez
            port: https
            scheme: HTTPS
          periodSeconds: 10
        name: metrics-server
        ports:
        - containerPort: 4443
          name: https
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /readyz
            port: https
            scheme: HTTPS
          periodSeconds: 10
        securityContext:
          readOnlyRootFilesystem: true
          runAsNonRoot: true
          runAsUser: 1000
        volumeMounts:
        - mountPath: /tmp
          name: tmp-dir
      nodeSelector:
        kubernetes.io/os: linux
      priorityClassName: system-cluster-critical
      serviceAccountName: metrics-server
      volumes:
      - emptyDir: {}
        name: tmp-dir
---
apiVersion: apiregistration.k8s.io/v1
kind: APIService
metadata:
  labels:
    k8s-app: metrics-server
  name: v1beta1.metrics.k8s.io
spec:
  group: metrics.k8s.io
  groupPriorityMinimum: 100
  insecureSkipTLSVerify: true
  service:
    name: metrics-server
    namespace: kube-system
  version: v1beta1
  versionPriority: 100
  
  ## 获取node和pod资源信息
  kubectl top node
  kubectl top pod

创建镜像

# 编写php代码
cat > index.php << 'EOF'
<?php
$x = 0.0001;
for ($i = 0; $i <= 1000000; $i++) {
$x += sqrt($x);
}
echo "OK!";
?>
EOF
# 创建Dockerfile
cat > dockerfile << 'EOF'
FROM php:5-apache
ADD index.php /var/www/html/index.php
RUN chmod a+rx index.php
EOF
# 构建镜像
docker build -t php:v1 .
# 编写资源清单
1.kubectl run php-apache --image=php:v1 --requests=cpu=200m --expose --port=80
2.vim php-apache.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: php-apache
spec:
  replicas: 1
  selector:
     matchLabels:
       run: php-apache
  template:
    metadata:
      labels:
        run: php-apache
    spec:
      containers:
      - image: php:v1
        imagePullPolicy: IfNotPresent
        name: php-apache
        resources:
          requests:
            cpu: 200m
# .编写HPA监控资源扩容php的Deployment 
kubectl autoscale deployment php-apache --cpu-percent=50 --min=1 --max=10
vim php-hpa.yaml
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: php-apache
  namespace: default
spec:
  maxReplicas: 10
  minReplicas: 1
  scaleTargetRef:
  apiVersion: apps/v1
  kind: Deployment
  name: php-apache
  targetCPUUtilizationPercentage: 50
# HPA资源清单意思
apiVersion: autoscaling/v1 						## HPA接口
kind: HorizontalPodAutoscaler				 	## HPA资源类型
metadata: 										## HPA元数据
name: php-apache 								## HPA资源名
namespace: default 								## 名称空间
spec: 											## HPA控制信息
maxReplicas: 15 								## 最多扩容15个副本
minReplicas: 1 									## 最少缩容到1个副本
scaleTargetRef: 								## HPA关联控制器
apiVersion: apps/v1 							## 控制器的接口
kind: Deployment 								## 控制器类型
name: php-apache 								## 控制器名字
targetCPUUtilizationPercentage: 50 				## CPU使用率达到50%则扩容
## 测试hpq是否可用自动扩缩容
while true; do curl -q 10.2.3.88 ; done
## 查看hpa自动扩缩容状态
 kubectl get hpa

天行健,君子以自强不息