Horizontal Pod Autoscaling,简称HPA,是Kubernetes中实现POD水平自动伸缩的功能,HPA可以可以基于CPU利用率或其他应用程序提供的度量指标自动缩放POD的数量
Pod水平自动伸缩特性由Kubernetes API资源和控制器实现,资源决定了控制器的行为。控制器会周期性的获取平均率,并与目标值相比较后来调整副本数量
限制
-不适合用于无法伸缩的对象,比如:DaemonSets
[root@master ~]# vim myhpa.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: myweb #集群名称
spec:
selector:
matchLabels:
app: apache #后端标签app:apache
replicas: 1 #只有1个POD
template:
metadata:
labels:
app: apache #标签
spec:
containers:
- name: apache
image: 192.168.1.100:5000/myos:httpd
ports:
- containerPort: 80
resources: #计算此计算器所需的资源
requests: #描述所需的最小计算资源量
cpu: 200m #计量单位,可以看作100milli
restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
name: web-service
spec:
ports:
- protocol: TCP
port: 80
targetPort: 80
selector:
app: apache
type: ClusterIP
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: my-app
annotations:
kubernetes.io/ingress.class: "nginx"
spec:
backend:
serviceName: web-service
servicePort: 80
---
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler #HPA资源内型
metadata:
name: myweb #HPA名称
spec:
minReplicas: 1 #最小保留POD数量
maxReplicas: 3 #最大保留POD数量
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: myweb #监视deployment名称
targetCPUUtilizationPercentage: 50 #CPU度量值
[root@master ~]# kubectl apply -f hpa-example.yaml
[root@master ~]# kubectl get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
myweb Deployment/myweb 0%/50% 1 3 1 15m
当容器的cpu占用超过 50% 的时候,自动扩展一个POD,依次扩展,一直到最大值
如果cpu访问不足 50% 的时候,每 300s 缩减一个 POD 节点,直到最小值时停止
访问测试可以使用镜像内提供的 info.php增加系统负载,从而查看状态信息
访问地址? http://ip.xx.xx.xx/info.php?id=1000000
[root@master ~]# kubectl get service
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.254.0.1 <none> 443/TCP 5d19h
myapache ClusterIP 10.254.105.21 <none> 80/TCP 4d1h
myheadless ClusterIP None <none> 80/TCP 3d23h
mynodeport NodePort 10.254.207.195 <none> 80:31341/TCP 3d23h
web-service ClusterIP 10.254.196.125 <none> 80/TCP 7m23s
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
myweb-7f89fc7b66-99xfx 1/1 Running 0 115s
myweb-7f89fc7b66-lvrhs 1/1 Running 0 7m29s
[root@master ~]# kubectl get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
myweb Deployment/myweb 70%/50% 1 3 2 7m34s
[root@master ~]#
[root@master ~]# kubectl get hpa -w #时实观看