基于Prometheus和K8S构建智能化告警系统
- 一、Prometheus对kubernetes的监控
- 二、node-exporter组件安装和配置
- 2.1、node-exporter介绍
- 2.2、安装node-exporter
- 【1】拉取镜像
- 【2】编写yaml文件
- 【3】运行pod
- 【4】获取数据
- 三、Prometheus server安装和配置
- 3.1、创建sa账号,对sa做rbac授权
- 3.2、创建prometheus数据存储目录
- 3.3、安装Prometheus server服务
- 【1】创建一个configmap存储卷,用来存放prometheus配置信息
- 【2】通过deployment部署prometheus
- 【3】给prometheus创建一个service
- 3.4、Prometheus热加载
- 四、可视化UI界面Grafana的安装和配置
- 4.1、Grafana介绍
- 4.2、Grafana安装
- 【1】导入镜像
- 【2】更新yaml文件
- 【3】检查是否部署成功
- 4.3、Grafana界面接入Prometheus数据源
- 【1】登录grafana,浏览器访问10.32.1.147:30262
- 【2】配置grafana界面
- 【3】导入监控模板
- 五、 安装kube-state-metrics组件
- 5.1、kube-state-metrics是什么
- 5.2、kube-state-metrics安装
- 【1】创建sa,并对sa授权
- 【2】安装kube-state-metrics组件
- 【3】创建service
- 5.3、Grafana导入模板,展示数据
一、Prometheus对kubernetes的监控
对于Kubernetes而言,我们可以把当中所有的资源分为几类:
• 基础设施层(Node):集群节点,为整个集群和应用提供运行时资源
• 容器基础设施(Container):为应用提供运行时环境
• 用户应用(Pod):Pod中会包含一组容器,它们一起工作,并且对外提供一个(或者一组)功能
• 内部服务负载均衡(Service):在集群内,通过Service在集群暴露应用功能,集群内应用和应用之间访问时提供内部的负载均衡
• 外部访问入口(Ingress):通过Ingress提供集群外的访问入口,从而可以使外部客户端能够访问到部署在Kubernetes集群内的服务
因此,如果要构建一个完整的监控体系,我们应该考虑,以下5个方面:
• 集群节点状态监控:从集群中各节点的kubelet服务获取节点的基本运行状态;
• 集群节点资源用量监控:通过Daemonset的形式在集群中各个节点部署Node Exporter采集节点的资源使用情况;
• 节点中运行的容器监控:通过各个节点中kubelet内置的cAdvisor中获取个节点中所有容器的运行状态和资源使用情况;
• 如果在集群中部署的应用程序本身内置了对Prometheus的监控支持,那么我们还应该找到相应的Pod实例,并从该Pod实例中获取其内部运行状态的监控指标。
• 对k8s本身的组件做监控:apiserver、scheduler、controller-manager、kubelet、kube-proxy
二、node-exporter组件安装和配置
机器规划:
我的实验环境使用的k8s集群是一个master节点和俩个node节点
master节点的机器ip是10.32.1.147,主机名是master
node1节点的机器ip是10.32.1.148,主机名是node01
node2节点的机器ip是10.32.1.149,主机名是node02
2.1、node-exporter介绍
node-exporter可以采集机器(物理机、虚拟机、云主机等)的监控指标数据,能够采集到的指标包括CPU, 内存,磁盘,网络,文件数等信息。
2.2、安装node-exporter
【1】拉取镜像
[root@master ~]# kubectl create ns monitor-sa
namespace/monitor-sa created
[root@master 2]# docker pull prom/node-exporter
Using default tag: latest
latest: Pulling from prom/node-exporter
Digest: sha256:f2269e73124dd0f60a7d19a2ce1264d33d08a985aed0ee6b0b89d0be470592cd
Status: Image is up to date for prom/node-exporter:latest
docker.io/prom/node-exporter:latest
【2】编写yaml文件
[root@master 2]# vim node-export.yaml
apiVersion: apps/v1
kind: DaemonSet #可以保证k8s集群的每个节点都运行完全一样的pod
metadata:
name: node-exporter
namespace: monitor-sa
labels:
name: node-exporter
spec:
selector:
matchLabels:
name: node-exporter
template:
metadata:
labels:
name: node-exporter
spec:
hostPID: true
hostIPC: true
hostNetwork: true
# hostNetwork、hostIPC、hostPID都为True时,表示这个Pod里的所有容器,会直接使用宿主机的网络,直接与宿主机进行IPC(进程间通信)通>信,可以看到宿主机里正在运行的所有进程。
# 加入了hostNetwork:true会直接将我们的宿主机的9100端口映射出来,从而不需要创建service 在我们的宿主机上就会有一个9100的端口
containers:
- name: node-exporter
image: prom/node-exporter:latest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 9100
resources:
requests:
cpu: 0.15 #这个容器运行至少需要0.15核cpu
securityContext:
privileged: true #开启特权模式
args:
- --path.procfs #配置挂载宿主机(node节点)的路径
- /host/proc
- --path.sysfs #配置挂载宿主机(node节点)的路径
- /host/sys
- --collector.filesystem.ignored-mount-points
- '"^/(sys|proc|dev|host|etc)($|/)"'
#通过正则表达式忽略某些文件系统挂载点的信息收集
volumeMounts:
- name: dev
mountPath: /host/dev
- name: proc
mountPath: /host/proc
- name: sys
mountPath: /host/sys
- name: rootfs
mountPath: /rootfs
#将主机/dev、/proc、/sys这些目录挂在到容器中,这是因为我们采集的很多节点数据都是通过这些文件来获取系统信息的。
tolerations:
- key: "node-role.kubernetes.io/master"
operator: "Exists"
effect: "NoSchedule"
volumes:
- name: proc
hostPath:
path: /proc
- name: dev
hostPath:
path: /dev
- name: sys
hostPath:
path: /sys
- name: rootfs
hostPath:
path: /
【3】运行pod
[root@master 2]# k apply -f node-export.yaml
daemonset.apps/node-exporter created
[root@master 2]# k get pod -n monitor-sa -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
node-exporter-l4txr 1/1 Running 0 32s 10.32.1.149 node02 <none> <none>
node-exporter-rk5kf 1/1 Running 0 32s 10.32.1.148 node01 <none> <none>
node-exporter-zxsch 1/1 Running 0 77s 10.32.1.147 master <none> <none>
[root@node01 ~]# ss -anlupt |grep 9100
tcp LISTEN 0 128 [::]:9100 [::]:* users:(("node_exporter",pid=10118,fd=3))
You have mail in /var/spool/mail/root
[root@node02 ~]# ss -anlupt |grep 9100
tcp LISTEN 0 128 [::]:9100 [::]:* users:(("node_exporter",pid=15314,fd=3))
You have mail in /var/spool/mail/root
【4】获取数据
node-export默认的监听端口是9100,可以看到当前主机获取到的所有监控数据
[root@master 2]# curl http://10.32.1.149:9100/metrics | grep node_cpu_seconds
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0# HELP node_cpu_seconds_total Seconds the CPUs spent in each mode.
# TYPE node_cpu_seconds_total counter
node_cpu_seconds_total{cpu="0",mode="idle"} 5.0940393e+06
node_cpu_seconds_total{cpu="0",mode="iowait"} 4090.52
node_cpu_seconds_total{cpu="0",mode="irq"} 0
node_cpu_seconds_total{cpu="0",mode="nice"} 3.13
node_cpu_seconds_total{cpu="0",mode="softirq"} 13194.74
node_cpu_seconds_total{cpu="0",mode="steal"} 0
node_cpu_seconds_total{cpu="0",mode="system"} 404041.49
node_cpu_seconds_total{cpu="0",mode="user"} 358361.89
node_cpu_seconds_total{cpu="1",mode="idle"} 5.10670262e+06
node_cpu_seconds_total{cpu="1",mode="iowait"} 3227.68
node_cpu_seconds_total{cpu="1",mode="irq"} 0
node_cpu_seconds_total{cpu="1",mode="nice"} 4.58
node_cpu_seconds_total{cpu="1",mode="softirq"} 9736.3
node_cpu_seconds_total{cpu="1",mode="steal"} 0
node_cpu_seconds_total{cpu="1",mode="system"} 380974.33
node_cpu_seconds_total{cpu="1",mode="user"} 365597.51
node_cpu_seconds_total{cpu="2",mode="idle"} 5.15063396e+06
node_cpu_seconds_total{cpu="2",mode="iowait"} 3682.42
node_cpu_seconds_total{cpu="2",mode="irq"} 0
node_cpu_seconds_total{cpu="2",mode="nice"} 3.14
node_cpu_seconds_total{cpu="2",mode="softirq"} 12857.83
node_cpu_seconds_total{cpu="2",mode="steal"} 0
node_cpu_seconds_total{cpu="2",mode="system"} 351735.74
node_cpu_seconds_total{cpu="2",mode="user"} 352276.66
node_cpu_seconds_total{cpu="3",mode="idle"} 5.16915161e+06
node_cpu_seconds_total{cpu="3",mode="iowait"} 3750.2
node_cpu_seconds_total{cpu="3",mode="irq"} 0
node_cpu_seconds_total{cpu="3",mode="nice"} 4.96
node_cpu_seconds_total{cpu="3",mode="softirq"} 9893.12
node_cpu_seconds_total{cpu="3",mode="steal"} 0
node_cpu_seconds_total{cpu="3",mode="system"} 342921.8
node_cpu_seconds_total{cpu="3",mode="user"} 343106.91
100 139k 0 139k 0 0 1757k 0 --:--:-- --:--:-- --:--:-- 1782k
#HELP:解释当前指标的含义,上面表示在每种模式下node节点的cpu花费的时间,以s为单位
#TYPE:说明当前指标的数据类型,上面是counter类型
node_cpu_seconds_total{cpu=“0”,mode=“idle”} :
cpu0上idle进程占用CPU的总时间,CPU占用时间是一个只增不减的度量指标,从类型中也可以看出node_cpu的数据类型是counter(计数器)
counter计数器:只是采集递增的指标
[root@master 2]# curl http://10.32.1.148:9100/metrics | grep node_load
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0# HELP node_load1 1m load average.
# TYPE node_load1 gauge
node_load1 0.46
# HELP node_load15 15m load average.
# TYPE node_load15 gauge
node_load15 0.44
# HELP node_load5 5m load average.
# TYPE node_load5 gauge
node_load5 0.47
100 141k 0 141k 0 0 1585k 0 --:--:-- --:--:-- --:--:-- 1605k
node_load1该指标反映了当前主机在最近一分钟以内的负载情况,系统的负载情况会随系统资源的使用而变化,因此node_load1反映的是当前状态,数据可能增加也可能减少,从注释中可以看出当前指标类型为gauge(标准尺寸)
gauge标准尺寸:统计的指标可增加可减少
三、Prometheus server安装和配置
3.1、创建sa账号,对sa做rbac授权
# 创建一个sa账号monitor
[root@master 2]# kubectl create serviceaccount monitor -n monitor-sa
serviceaccount/monitor created
# 把sa账号monitor通过clusterrolebinding绑定到clusterrole上
[root@master 2]# kubectl create clusterrolebinding monitor-clusterrolebinding -n monitor-sa --clusterrole=cluster-admin --serviceaccount=monitor-sa:monitor
clusterrolebinding.rbac.authorization.k8s.io/monitor-clusterrolebinding created
注意:有的同学执行上面授权也会报错,那就需要下面的授权命令:
kubectl create clusterrolebinding monitor-clusterrolebinding-1 -n monitor-sa --clusterrole=cluster-admin --user=system:serviceaccount:monitor:monitor-sa
3.2、创建prometheus数据存储目录
在k8s集群的xianchaonode1节点上创建数据存储目录
[root@master 2]# mkdir /data
[root@master 2]# cd /data
[root@master data]# chmod 777 /data/
3.3、安装Prometheus server服务
【1】创建一个configmap存储卷,用来存放prometheus配置信息
vim prometheus-cfg.yaml
---
kind: ConfigMap
apiVersion: v1
metadata:
labels:
app: prometheus
name: prometheus-config
namespace: monitor-sa
data:
prometheus.yml: |
global: #指定prometheus的全局配置,比如采集间隔,抓取超时时间等
scrape_interval: 15s #采集目标主机监控数据的时间间隔,默认为1m
scrape_timeout: 10s #数据采集超时时间,默认10s
evaluation_interval: 1m #触发告警生成alert的时间间隔,默认是1m
scrape_configs: #配置数据源,称为target,每个target用job_name命名。又分为静态配置和服务发现
- job_name: 'kubernetes-node'
kubernetes_sd_configs: # *_sd_configs 指定的是k8s的服务发现
- role: node #使用node角色,它使用默认的kubelet提供的http端口来发现集群中每个node节点
relabel_configs: #重新标记
- source_labels: [__address__] #配置的原始标签,匹配地址
regex: '(.*):10250' #匹配带有10250端口的url
replacement: '${1}:9100' #把匹配到的ip:10250的ip保留
target_label: __address__ #新生成的url是${1}获取到的ip:9100
action: replace #动作替换
- action: labelmap
regex: __meta_kubernetes_node_label_(.+) #匹配到下面正则表达式的标签会被保留,如果不做regex正则的话,默认只是会显示instance标签
- job_name: 'kubernetes-node-cadvisor' #抓取cAdvisor数据,是获取kubelet上/metrics/cadvisor接口数据来获取容器的资源使用情况
kubernetes_sd_configs:
- role: node
scheme: https
tls_config:
ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
relabel_configs:
- action: labelmap #把匹配到的标签保留
regex: __meta_kubernetes_node_label_(.+) #保留匹配到的具有__meta_kubernetes_node_label的标签
- target_label: __address__ #获取到的地址:__address__="192.168.192.11:10250"
replacement: kubernetes.default.svc:443 #把获取到的地址替换成新的地址kubernetes.default.svc:443
- source_labels: [__meta_kubernetes_node_name]
regex: (.+) #把原始标签中__meta_kubernetes_node_name值匹配到
target_label: __metrics_path__ #获取__metrics_path__对应的值
replacement: /api/v1/nodes/${1}/proxy/metrics/cadvisor
#把metrics替换成新的值api/v1/nodes/k8s-master1/proxy/metrics/cadvisor
#${1}是__meta_kubernetes_node_name获取到的值
#新的url就是https://kubernetes.default.svc:443/api/v1/nodes/k8s-master1/proxy/metrics/cadvisor
- job_name: 'kubernetes-apiserver'
kubernetes_sd_configs:
- role: endpoints #使用k8s中的endpoint服务发现,采集apiserver 6443端口获取到的数据
scheme: https
tls_config:
ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
relabel_configs:
- source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name] #[endpoint这个对象的名称空间,endpoint对象的服务名,exnpoint的端口名称]
action: keep #采集满足条件的实例,其他实例不采集
regex: default;kubernetes;https #正则匹配到的默认空间下的service名字是kubernetes,协议是https的endpoint类型保留下来
- job_name: 'kubernetes-service-endpoints'
kubernetes_sd_configs:
- role: endpoints
relabel_configs:
- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape]
action: keep
regex: true
#重新打标仅抓取到的具有"prometheus.io/scrape: true"的annotation的端点, 意思是说如果某个service具有prometheus.io/scrape = true的annotation声明则抓取,annotation本身也是键值结构, 所以这里的源标签设置为键,而regex设置值true,当值匹配到regex设定的内容时则执行keep动作也就是保留,其余则丢弃。
- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme]
action: replace
target_label: __scheme__
regex: (https?)
#重新设置scheme,匹配源标签__meta_kubernetes_service_annotation_prometheus_io_scheme也就是prometheus.io/scheme annotation,如果源标签的值匹配到regex,则把值替换为__scheme__对应的值。
- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
#应用中自定义暴露的指标,也许你暴露的API接口不是/metrics这个路径,那么你可以在这个POD对应的service中做一个 "prometheus.io/path = /mymetrics" 声明,上面的意思就是把你声明的这个路径赋值给__metrics_path__, 其实就是让prometheus来获取自定义应用暴露的metrices的具体路径, 不过这里写的要和service中做好约定,如果service中这样写 prometheus.io/app-metrics-path: '/metrics' 那么你这里就要__meta_kubernetes_service_annotation_prometheus_io_app_metrics_path这样写。
- source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port]
action: replace
target_label: __address__
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
#暴露自定义的应用的端口,就是把地址和你在service中定义的 "prometheus.io/port = <port>" 声明做一个拼接, 然后赋值给__address__,这样prometheus就能获取自定义应用的端口,然后通过这个端口再结合__metrics_path__来获取指标,如果__metrics_path__值不是默认的/metrics那么就要使用上面的标签替换来获取真正暴露的具体路径。
- action: labelmap #保留下面匹配到的标签
regex: __meta_kubernetes_service_label_(.+)
- source_labels: [__meta_kubernetes_namespace]
action: replace #替换__meta_kubernetes_namespace变成kubernetes_namespace
target_label: kubernetes_namespace
- source_labels: [__meta_kubernetes_service_name]
action: replace
target_label: kubernetes_name
[root@master 2]# kubectl apply -f prometheus-cfg.yaml
configmap/prometheus-config created
[root@master 2]# kubectl get cm -n monitor-sa
NAME DATA AGE
kube-root-ca.crt 1 3h25m
prometheus-config 1 41s
【2】通过deployment部署prometheus
[root@master 2]# cat prometheus-deploy.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: prometheus-server
namespace: monitor-sa
labels:
app: prometheus
spec:
replicas: 1
selector:
matchLabels:
app: prometheus
component: server
#matchExpressions:
#- {key: app, operator: In, values: [prometheus]}
#- {key: component, operator: In, values: [server]}
template:
metadata:
labels:
app: prometheus
component: server
annotations:
prometheus.io/scrape: 'false'
spec:
nodeName: node01 #指定pod调度到哪个节点上
serviceAccountName: monitor
containers:
- name: prometheus
image: prom/prometheus:v2.2.1
imagePullPolicy: IfNotPresent
command:
- prometheus
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus #数据存储目录
- --storage.tsdb.retention=720h #数据保存时长
- --web.enable-lifecycle #开启热加载
ports:
- containerPort: 9090
protocol: TCP
volumeMounts:
- mountPath: /etc/prometheus/prometheus.yml
name: prometheus-config
subPath: prometheus.yml
- mountPath: /prometheus/
name: prometheus-storage-volume
volumes:
- name: prometheus-config
configMap:
name: prometheus-config
items:
- key: prometheus.yml
path: prometheus.yml
mode: 0644
- name: prometheus-storage-volume
hostPath:
path: /data
type: Directory
[root@master 2]# kubectl apply -f prometheus-deploy.yaml
deployment.apps/prometheus-server created
[root@master 2]# k get pod -n monitor-sa
NAME READY STATUS RESTARTS AGE
node-exporter-tjlfj 1/1 Running 0 65m
node-exporter-v8fc5 1/1 Running 0 64m
node-exporter-zxsch 1/1 Running 0 61m
prometheus-server-5f95484889-rklm8 1/1 Running 0 7m44s
【3】给prometheus创建一个service
vim prometheus-svc.yaml
---
apiVersion: v1
kind: Service
metadata:
name: prometheus
namespace: monitor-sa
labels:
app: prometheus
spec:
type: NodePort
ports:
- port: 9090
targetPort: 9090
protocol: TCP
nodePort: 31000
selector:
app: prometheus
component: server
[root@master 2]# k apply -f prometheus-svc.yaml
service/prometheus created
[root@master 2]# kubectl get svc -n monitor-sa
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
prometheus NodePort 10.104.116.119 <none> 9090:31000/TCP 5m14s
点击页面的Status->Targets,如看到所有 Target 状态都为 UP,说明我们配置的服务发现可以正常采集数据
3.4、Prometheus热加载
为了每次修改配置文件可以热加载prometheus,也就是不停止prometheus,就可以使配置生效,想要使配置生效可用如下热加载命令:
[root@master 2]# kubectl get pods -n monitor-sa -o wide -l app=prometheus
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
prometheus-server-5f95484889-rklm8 1/1 Running 0 112m 10.244.196.177 node01 <none> <none>
# 想要使配置生效可用如下命令热加载:
[root@master ~]# curl -X POST http://10.244.196.177:9090/-/reload
# 这条命令能执行成功的原因是:在prometheus-deploy.yaml中开启了热加载
# - --web.enable-lifecycle #开启热加载
热加载速度比较慢,可以暴力重启prometheus
执行如下强制删除:
kubectl delete -f prometheus-cfg.yaml
kubectl delete -f prometheus-deploy.yaml
然后再通过apply更新:
kubectl apply -f prometheus-cfg.yaml
kubectl apply -f prometheus-deploy.yaml
注意:
线上最好热加载,暴力删除可能造成监控数据的丢失
四、可视化UI界面Grafana的安装和配置
4.1、Grafana介绍
Grafana是一个跨平台的开源的度量分析和可视化工具,可以将采集的数据可视化的展示,并及时通知给告警接收方。它主要有以下六大特点:
- 1、展示方式 快速灵活的客户端图表,面板插件有许多不同方式的可视化指标和日志,官方库中具有丰富的仪表盘插件,比如热图、折线图、图表等多种展示方式;
- 2、数据源 Graphite,InfluxDB,OpenTSDB,Prometheus,Elasticsearch,CloudWatch和KairosDB等;
- 3、通知提醒 以可视方式定义最重要指标的警报规则,Grafana将不断计算并发送通知,在数据达到阈值时通过Slack、PagerDuty等获得通知;
- 4、混合展示 在同一图表中混合使用不同的数据源,可以基于每个查询指定数据源,甚至自定义数据源;
- 5、注释 使用来自不同数据源的丰富事件注释图表,将鼠标悬停在事件上会显示完整的事件元数据和标记。
4.2、Grafana安装
【1】导入镜像
安装Grafana需要的镜像heapster-grafana-amd64_v5_0_4.tar.gz,把镜像上传到k8s的工作节点node02上,手动解压:
[root@node02 package]# ctr -n=k8s.io images import heapster-grafana-amd64_v5_0_4.tar.gz
unpacking k8s.gcr.io/heapster-grafana-amd64:v5.0.4 (sha256:1703015b12590c4c0a34d82e8c69c4e87a6f2303107034c720624e7cd74380da)...done
You have mail in /var/spool/mail/root
# 如果k8s版本是1.24之前的,就用docker load -i导入镜像
【2】更新yaml文件
[root@master 2]# cat grafana.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: monitoring-grafana
namespace: kube-system
spec:
replicas: 1
selector:
matchLabels:
task: monitoring
k8s-app: grafana
template:
metadata:
labels:
task: monitoring
k8s-app: grafana
spec:
containers:
- name: grafana
image: k8s.gcr.io/heapster-grafana-amd64:v5.0.4
imagePullPolicy: IfNotPresent
ports:
- containerPort: 3000
protocol: TCP
volumeMounts:
- mountPath: /etc/ssl/certs
name: ca-certificates
readOnly: true
- mountPath: /var
name: grafana-storage
env:
- name: INFLUXDB_HOST
value: monitoring-influxdb
- name: GF_SERVER_HTTP_PORT
value: "3000"
# The following env variables are required to make Grafana accessible via
# the kubernetes api-server proxy. On production clusters, we recommend
# removing these env variables, setup auth for grafana, and expose the grafana
# service using a LoadBalancer or a public IP.
- name: GF_AUTH_BASIC_ENABLED
value: "false"
- name: GF_AUTH_ANONYMOUS_ENABLED
value: "true"
- name: GF_AUTH_ANONYMOUS_ORG_ROLE
value: Admin
- name: GF_SERVER_ROOT_URL
# If you're only using the API Server proxy, set this value instead:
# value: /api/v1/namespaces/kube-system/services/monitoring-grafana/proxy
value: /
volumes:
- name: ca-certificates
hostPath:
path: /etc/ssl/certs
- name: grafana-storage
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
labels:
# For use as a Cluster add-on (https://github.com/kubernetes/kubernetes/tree/master/cluster/addons)
# If you are NOT using this as an addon, you should comment out this line.
kubernetes.io/cluster-service: 'true'
kubernetes.io/name: monitoring-grafana
name: monitoring-grafana
namespace: kube-system
spec:
# In a production setup, we recommend accessing Grafana through an external Loadbalancer
# or through a public IP.
# type: LoadBalancer
# You could also use NodePort to expose the service at a randomly-generated port
# type: NodePort
ports:
- port: 80
targetPort: 3000
selector:
k8s-app: grafana
type: NodePort
【3】检查是否部署成功
[root@master 2]# kubectl apply -f grafana.yaml
deployment.apps/monitoring-grafana created
service/monitoring-grafana created
# 检查是否部署成功
[root@master 2]# kubectl get pods -n kube-system -l task=monitoring
NAME READY STATUS RESTARTS AGE
monitoring-grafana-d47cdf886-vxwkg 1/1 Running 0 26s
4.3、Grafana界面接入Prometheus数据源
# 查看grafana前端的service
[root@master 2]# kubectl get svc -n kube-system | grep grafana
monitoring-grafana NodePort 10.97.90.36 <none> 80:30262/TCP 2m14s
【1】登录grafana,浏览器访问10.32.1.147:30262
【2】配置grafana界面
选择Create your first data source
Name: Prometheus
Type: Prometheus
HTTP 处的URL写 如下: http://prometheus.monitor-sa.svc:9090
点击左下角Save & Test,出现如下Data source is working,说明prometheus数据源成功的被grafana接入了
【3】导入监控模板
监控模板搜索: https://grafana.com/dashboards?dataSource=prometheus&search=kubernetes
可直接导入node_exporter.json监控模板,这个可以把node节点指标显示出来,node_exporter.json在课件里
可直接导入docker_rev1.json,显示容器资源指标的,docker_rev1.json在课件里
导入docker_rev1.json监控模板,步骤和上面导入node_exporter.json步骤一样,导入之后显示如下:
五、 安装kube-state-metrics组件
5.1、kube-state-metrics是什么
kube-state-metrics通过监听API Server生成有关资源对象的状态指标,比如Node、Pod,需要注意的是kube-state-metrics只是简单的提供一个metrics数据,并不会存储这些指标数据,所以我们可以使用Prometheus来抓取这些数据然后存储,主要关注的是业务相关的一些元数据,比如Pod副本状态等;调度了多少个replicas?现在可用的有几个?多少个Pod是running/stopped/terminated状态?Pod重启了多少次?我有多少job在运行中。
5.2、kube-state-metrics安装
【1】创建sa,并对sa授权
在k8s的控制节点生成一个kube-state-metrics-rbac.yaml文件,kube-state-metrics-rbac.yaml文件在课件,大家上传到k8s的控制节点即可:
[root@master 2]# cat kube-state-metrics-rbac.yaml
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: kube-state-metrics
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: kube-state-metrics
rules:
- apiGroups: [""]
resources: ["nodes", "pods", "services", "resourcequotas", "replicationcontrollers", "limitranges", "persistentvolumeclaims", "persistentvolumes", "namespaces", "endpoints"]
verbs: ["list", "watch"]
- apiGroups: ["extensions"]
resources: ["daemonsets", "deployments", "replicasets"]
verbs: ["list", "watch"]
- apiGroups: ["apps"]
resources: ["statefulsets"]
verbs: ["list", "watch"]
- apiGroups: ["batch"]
resources: ["cronjobs", "jobs"]
verbs: ["list", "watch"]
- apiGroups: ["autoscaling"]
resources: ["horizontalpodautoscalers"]
verbs: ["list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: kube-state-metrics
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: kube-state-metrics
subjects:
- kind: ServiceAccount
name: kube-state-metrics
namespace: kube-system
[root@master 2]# kubectl apply -f kube-state-metrics-rbac.yaml
serviceaccount/kube-state-metrics created
clusterrole.rbac.authorization.k8s.io/kube-state-metrics created
clusterrolebinding.rbac.authorization.k8s.io/kube-state-metrics created
【2】安装kube-state-metrics组件
安装kube-state-metrics组件需要的镜像在课件,可上传到k8s各个工作节点,手动解压:
[root@node01 package]# ctr -n=k8s.io images import kube-state-metrics_1_9_0.tar.gz
unpacking quay.io/coreos/kube-state-metrics:v1.9.0 (sha256:bf40aa1452dcefe34680c595995af1f4a72b7a480b3597fe863a3a5c4e8dde42)...done
[root@node02 package]# ctr -n=k8s.io images import kube-state-metrics_1_9_0.tar.gz
unpacking quay.io/coreos/kube-state-metrics:v1.9.0 (sha256:bf40aa1452dcefe34680c595995af1f4a72b7a480b3597fe863a3a5c4e8dde42)...done
master节点生成kube-state-metrics-deploy.yaml文件
[root@master 2]# cat kube-state-metrics-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: kube-state-metrics
namespace: kube-system
spec:
replicas: 1
selector:
matchLabels:
app: kube-state-metrics
template:
metadata:
labels:
app: kube-state-metrics
spec:
serviceAccountName: kube-state-metrics
containers:
- name: kube-state-metrics
image: quay.io/coreos/kube-state-metrics:v1.9.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
# 查看kube-state-metrics是否部署成功
[root@master 2]# kubectl apply -f kube-state-metrics-deploy.yaml
deployment.apps/kube-state-metrics created
[root@master 2]# kubectl get pods -n kube-system -l app=kube-state-metrics
NAME READY STATUS RESTARTS AGE
kube-state-metrics-7594ddfc96-k2jft 1/1 Running 0 5s
【3】创建service
master节点生成kube-state-metrics-svc.yaml文件
[root@master 2]# cat kube-state-metrics-svc.yaml
apiVersion: v1
kind: Service
metadata:
annotations:
prometheus.io/scrape: 'true'
name: kube-state-metrics
namespace: kube-system
labels:
app: kube-state-metrics
spec:
ports:
- name: kube-state-metrics
port: 8080
protocol: TCP
selector:
app: kube-state-metrics
[root@master 2]# kubectl apply -f kube-state-metrics-svc.yaml
service/kube-state-metrics created
# 查看service是否创建成功
[root@master 2]# kubectl get svc -n kube-system | grep kube-state-metrics
kube-state-metrics ClusterIP 10.107.173.99 <none> 8080/TCP 27s
5.3、Grafana导入模板,展示数据
在grafana web界面导入Kubernetes Cluster (Prometheus)-1577674936972.json和Kubernetes cluster monitoring (via Prometheus) (k8s 1.16)-1577691996738.json
这俩个json模板课件里面有,需要的可与我联系。
Kubernetes Cluster (Prometheus)-1577674936972.json 展示效果
Kubernetes cluster monitoring (via Prometheus) (k8s 1.16)-1577691996738.json展示效果