1.官网地址
HorizontalPodAutoscaler 演练 | Kubernetes
2.HPA全称HorizontalPodAutoscaler 自动更新工作负载资源 (例如 Deployment 或者 StatefulSet), 目的是自动扩缩工作负载以满足需求。
HorizontalPodAutoscaler 是如何工作的
3.实例,创建HPA监控资源,在流量大时自动扩容deployment中pod
[root@master ~]# cat nginx.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
selector:
matchLabels:
run: nginx
template:
metadata:
labels:
run: nginx
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
resources:
limits:
cpu: 40m
requests:
cpu: 20m
---
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
run: nginx
spec:
ports:
- port: 80
selector:
run: nginx
kubectl apply -f nginx.yaml
deployment.apps/nginx created
service/nginx unchanged
[root@master ~]# kubectl get deployments.apps nginx
NAME READY UP-TO-DATE AVAILABLE AGE
nginx 1/1 1 1 2m13s
[root@master ~]# kubectl get svc nginx
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
nginx ClusterIP 10.96.243.67 <none> 80/TCP 2m47s
创建HPA
[root@master ~]# kubectl autoscale deployment nginx --cpu-percent=30 --min=1 --max=10
horizontalpodautoscaler.autoscaling/nginx autoscaled
[root@master ~]# kubectl get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
nginx Deployment/nginx 0%/30% 1 10 1 86s
查看svc的CLUSTER-IP,配置本地解析,使用ab进行压测。(cluster-ip只能在集群内访问)
[root@master ~]# kubectl get svc nginx
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
nginx ClusterIP 10.96.243.67 <none> 80/TCP 6m32s
[root@master ~]# vim /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.8.3 master
192.168.8.4 node-1
192.168.8.5 node-2
10.96.243.67 www.example.com
安装ab命令
yum -y install httpd-tools
使用ab命令进行压测
ab -n 10000000 -c 10000 http://www.example.com/
#新开窗口监测hpa
[root@master ~]# kubectl get hpa nginx --watch
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
nginx Deployment/nginx 0%/30% 1 10 1 5m30s
nginx Deployment/nginx 105%/30% 1 10 1 6m16s
nginx Deployment/nginx 105%/30% 1 10 4 6m31s
nginx Deployment/nginx 5%/30% 1 10 4 6m46s
nginx Deployment/nginx 0%/30% 1 10 4 7m46s
#新开窗口检测deployment
[root@master ~]# kubectl get deployments.apps nginx --watch
NAME READY UP-TO-DATE AVAILABLE AGE
nginx 1/1 1 1 10m
nginx 1/4 1 1 10m
nginx 1/4 1 1 10m
nginx 1/4 1 1 10m
nginx 1/4 4 1 10m
nginx 2/4 4 2 10m
nginx 3/4 4 3 10m
nginx 4/4 4 4 10m
等到流量下去的时候,副本数会减少
[root@master ~]# kubectl get deployments.apps nginx --watch
NAME READY UP-TO-DATE AVAILABLE AGE
nginx 4/4 4 4 13m
nginx 1/1 1 1 16m