服务的伸缩性
伸缩性是指系统可以根据需求和成本调整自身处理能力的一种能力,构建可伸缩的服务有可能要求服务的处理能力在数天内扩大数倍,又需要在数天后将处理能力还原回去。
在Kubernetes集群中我们可以通过Replication Controller的scale机制完成服务的扩容或缩容,实现具有伸缩性的服务。
创建如下tomcat的RC:
apiVersion: v1
kind: ReplicationController
metadata:
name: tomcat
spec:
replicas: 2
template:
metadata:
labels:
app: tomcat
spec:
containers:
- name: tomcat
image: tomcat
ports:
- containerPort: 8080
resources:
requests:
cpu: "200m"
limits:
cpu: "500m"创建如下tomcat的svc:
apiVersion: v1
kind: Service
metadata:
name: tomcat
spec:
type: NodePort
ports:
- port: 8080
nodePort: 31000
selector:
app: tomcatkubectl sacle手动伸缩
Pod扩容:
kubectl scale rc tomcat --replicas=5
kubectl get pod -o wide | grep tomcat
tomcat-8dxf1 1/1 Running 0 1m 10.244.1.3 cent2
tomcat-j97tf 1/1 Running 0 1m 10.244.4.15 cent1
tomcat-ng3zk 1/1 Running 0 1m 10.244.1.2 cent2
tomcat-tjq4n 1/1 Running 0 14m 10.244.4.12 cent1
tomcat-zg2qj 1/1 Running 0 14m 10.244.4.14 cent1Pod缩容:
kubectl scale rc tomcat --replicas=2
kubectl get pod -o wide | grep tomcat
tomcat-tjq4n 1/1 Running 0 18m 10.244.4.12 cent1
tomcat-zg2qj 1/1 Running 0 18m 10.244.4.14 cent1在Dashboard的RC页面更容易的完成Pod的伸缩。
kubectl autoscale自动伸缩
Kubernetes有一个HPA(Horizontal Pod Autoscaler)的东东,可以实现基于CPU使用率的Pod自动伸缩的功能。
HPA基于Master Node上的kube-controller-manager服务启动参数--horizontal-pod-autoscaler-sync-period定义的时长(默认为30秒),周期性的检测Pod的CPU使用率(需要事先安装heapster)。使用kubeadm初始化的集群,如果需要设置--horizontal-pod-autoscaler-sync-period可以在Master Node上的/etc/kubernetes/manifests/kube-controller-manager.json中修改。
kubectl autoscale rc tomcat --min=1 --max=6 --cpu-percent=25
replicationcontroller "tomcat" autoscaled查看创建的hpa,结果发现当前的CPU使用率CURRENT显示为waiting,于是怀疑heapster中没有CPU统计数据
kubectl get hpa tomcat
NAME REFERENCE TARGET CURRENT MINPODS MAXPODS AGE
tomcat ReplicationController/tomcat 25% <waiting> 1 6 13s查看hpa的事件,kubectl describe hpa,有这些错误信息MetricsNotAvailableYet unable to get metrics for resource cpu: no metrics returned from heapster。因为heapster的默认的启动参数是--source=kubernetes:https://kubernetes.default,因为使用的是域名,确定是dns解析出问题了,后来检查flannel相关Pod,修复后正常。
kubectl get hpa tomcat
NAME REFERENCE TARGET CURRENT MINPODS MAXPODS AGE
tomcat ReplicationController/tomcat 25% 0% 1 6 19m对tomcat service进行压力测试
kubectl run -i --tty load-generator --image=busybox /bin/sh
If you don't see a command prompt, try pressing enter.
/ # while true; do wget -q -O- http://tomcat.default.svc.cluster.local:8080 > /dev/null; done或直接在Node上运行:
while true; do wget -q -O- http://192.168.61.100:31000 > /dev/null; done查看hpa状态:
kubectl get hpa tomcat
NAME REFERENCE TARGET CURRENT MINPODS MAXPODS AGE
tomcat ReplicationController/tomcat 25% 123% 1 6 26m查看Pod:
kubectl get pod
NAME READY STATUS RESTARTS AGE
tomcat-29gzk 1/1 Running 0 3m
tomcat-c01bc 1/1 Running 0 3m
tomcat-cx34q 1/1 Running 0 3m
tomcat-fxw1l 1/1 Running 0 27m当停止压力测试之后,过一段时间,Pod数量又会恢复到1。
另外也可以使用yml文件来定义创建,参考HorizontalPodAutoscaler v1