metrics-server
1.作用
metrics-server::用于监测node,pod等的CPU,内存使用情况。
2.下载地址
3.需改动的文件
3.1 metrics-server/deploy/1.8+/metrics-server-deployment.yaml
直接替换为以下内容
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: metrics-server
namespace: kube-system
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: metrics-server
namespace: kube-system
labels:
k8s-app: metrics-server
spec:
selector:
matchLabels:
k8s-app: metrics-server
template:
metadata:
name: metrics-server
labels:
k8s-app: metrics-server
spec:
serviceAccountName: metrics-server
volumes:
# mount in tmp so we can safely use from-scratch images and/or read-only containers
- name: tmp-dir
emptyDir: {}
containers:
- name: metrics-server
image: k8s.gcr.io/metrics-server-amd64:v0.3.6
args:
- --cert-dir=/tmp
- --secure-port=4443
ports:
- name: main-port
containerPort: 4443
protocol: TCP
securityContext:
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 1000
imagePullPolicy: Always
volumeMounts:
- name: tmp-dir
mountPath: /tmp
nodeSelector:
beta.kubernetes.io/os: linux
3.2 metrics-server/deploy/1.8+/metrics-server-service.yaml
直接替换为以下内容
---
apiVersion: v1
kind: Service
metadata:
name: metrics-server
namespace: kube-system
labels:
kubernetes.io/name: "Metrics-server"
kubernetes.io/cluster-service: "true"
spec:
selector:
k8s-app: metrics-server
ports:
- port: 443
protocol: TCP
targetPort: 443
4.启动应用
将metrics-server拷贝到/opt目录下
执行以下命令启动应用:
5.查看效果
kubectl apply -f /opt/metrics-server/deploy/1.8+/
启动几分钟后,可执行以下的指令进行验证
kubectl top pods
kubectl top nodes
6.使用场景-HPA
HPA(弹性伸缩)需要采集性能指标,根据CPU,或者内存的使用情况,对pod进行扩容,或者缩容。
6.1 创建实例
将以下nginx.yml文件放到/opt目录下,执行以下命令
kubectl apply -f /opt/nginx.yml
yml文件内容如下
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-demo2
spec:
replicas: 1
selector:
matchLabels:
app: nginx-demo2
template:
metadata:
labels: # Pod副本拥有的标签,对应RC的Selector
app: nginx-demo2
spec:
containers:
- name: nginx-demo2
image: nginx:latest
ports:
- containerPort: 80 # 容器应用监听的端
# 下面指标是用来配合HPA使用
resources:
requests:
cpu: 0.005
memory: 64Mi
limits:
cpu: 0.05
memory: 128Mi
---
apiVersion: v1
kind: Service
metadata:
name: nginx-demo2
namespace: default
labels:
app: nginx-demo2
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
nodePort: 31113
selector:
app: nginx-demo2
---
#引入HPA,可对pod进行弹性伸缩
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: nginx-hpa
labels:
app: nginx-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx-demo2
minReplicas: 1 #最小副本数
maxReplicas: 10 #最大副本数
targetCPUUtilizationPercentage: 50 #cpu占用率达到50%触发
6.2 查看
kubectl get hpa
此时副本数应该是1个,CPU使用率应该是0。
6.3 压测
busybox镜像根据自己的镜像仓库更改
kubectl run --generator=run-pod/v1 -i --tty load-generator --image=busybox:latest /bin/sh
ip:端口根据实际情况更改
while true; do wget -q -O- http://ip:port/;
操作
done
退出压测
Ctrl+c
#exit
6.4 查看应用性能情况
查看应用CPU,内存使用情况;以及生成的副本数量
kubectl get hpa
查看应用生成的副本情况
kubectl get pods
注意:
执行伸缩操作后,会冷却一段时间,不再进行伸缩操作。
默认扩容3分钟,默认缩容为5分钟。
避免频繁的扩缩Pod,造成集群压力大,防止应用访问不稳定。