基于 Prometheus+Grafana+Alertmanager 搭建 K8S 云平台系统(附配置告警至QQ、钉钉)

news/2024/12/24 1:51:44/文章来源:https://www.cnblogs.com/misakivv/p/18450614

目录
  • 一、机器规划
  • 二、部署安装 node-exporter、prometheus、Grafana、kube-state-metrics
    • 1、创建 monitor-sa 命名空间
    • 2、安装node-exporter组件
      • 2.1、说明
      • 2.2、应用资源清单
      • 2.3、通过node-exporter采集数据
    • 3、k8s 集群中部署 prometheus
      • 3.1、创建一个 sa 账号
      • 3.2、将 sa 账号 monitor 通过 clusterrolebing 绑定到 clusterrole 上
      • 3.3、创建数据目录
      • 3.4、安装prometheus
        • 3.4.1、将 prometheus.yml 文件以 ConfigMap 的形式进行管理
        • 3.4.2、应用 cm 资源清单
        • 3.4.3、通过 Deployment 部署 prometheus
        • 3.4.4、应用 prometheus 资源清单
        • 3.4.5、给 prometheus 的 pod 创建一个 svc
        • 3.4.6、应用 svc 资源清单
      • 3.5、访问prometheus UI界面
      • 3.6、查看配置的服务发现
    • 4、prometheus热更新
      • 4.1、热加载 prometheus
      • 4.2、暴力重启 prometheus
    • 5、Grafana安装和配置
      • 5.1、下载 Grafana 需要的镜像
      • 5.2、在 k8s 集群各个节点导入 Grafana 镜像
      • 5.3、master 节点创建 grafana.yaml
      • 5.4、查看 Grafana 的 pod 和 svc
      • 5.5、查看 Grafana UI 界面
      • 5.6、给 Grafana 接入 Prometheus 数据源
      • 5.7、获取监控模板
      • 5.8、导入监控模板
    • 6、安装配置 kube-state-metrics 组件
      • 6.1、什么是 kube-state-metrics
      • 6.2、创建 sa ,并进行授权
      • 6.3、创建并应用 kube-state-metrics-deploy.yaml 文件
      • 6.4、创建并应用 kube-state-metrics-svc.yaml 文件
      • 6.5、获取 kube-state-metrics json 文件
      • 6.6、向 Grafana 导入 kube-state-metrics json 文件
  • 三、安装和配置 Alertmanager -- 发送告警到 QQ 邮箱
    • 1、将 alertmanager-cm.yaml 文件以 cm 形式进行管理
      • 1.1、alertmanager配置文件说明
    • 2、重新生成并应用 prometheus-cfg.yaml 文件
    • 3、重新生成 prometheus-deploy.yaml 文件
      • 3.1、创建一个名为 etcd-certs 的 Secret
      • 3.2、应用 prometheus-deploy.yaml 文件
    • 4、重新生成并创建 alertmanager-svc.yaml 文件
    • 5、访问 prometheus UI 界面
      • 5.1、【error】kube-controller-manager、etcd、kube-proxy、kube-scheduler 组件 connection refused
        • 5.1.1、kube-proxy
        • 5.1.2、kube-controller-manager
        • 5.1.3、kube-schedule
        • 5.1.4、etcd
    • 6、点击Alerts,查看
    • 7、把controller-manager的cpu使用率大于90%展开
    • 8、登录 alertmanager UI
    • 9、登录 QQ 邮箱查看告警信息
  • 四、配置 Alertmanager 报警 -- 发送告警到钉钉
    • 1、手机端拉群
    • 2、创建自定义机器人
    • 3、获取钉钉的 Webhook 插件
    • 4、启动钉钉告警插件
    • 5、对 alertmanager-cm.yaml 文件做备份
    • 6、重新生成新的 alertmanager-cm.yaml 文件
    • 7、重建资源以生效
    • 8、效果

一、机器规划

角色 主机名 ip 地址
master k8s-master1 192.168.112.10
node k8s-node1 192.168.112.20
node k8s-node2 192.168.112.30
平台 VMware Workstation
操作系统 CentOS Linux release 7.9.2009 (Core)
内存、CPU 4C4G
磁盘大小 20G SCSI

二、部署安装 node-exporter、prometheus、Grafana、kube-state-metrics

1、创建 monitor-sa 命名空间

master 节点操作

kubectl create ns monitor-sa

2、安装node-exporter组件

master 节点操作

cat >> node-export.yaml  <<EOF
apiVersion: apps/v1
kind: DaemonSet
metadata:name: node-exporternamespace: monitor-salabels:name: node-exporter
spec:selector:matchLabels:name: node-exportertemplate:metadata:labels:name: node-exporterspec:hostPID: truehostIPC: truehostNetwork: truecontainers:- name: node-exporterimage: prom/node-exporter:v0.16.0ports:- containerPort: 9100resources:requests:cpu: 0.15securityContext:privileged: trueargs:- --path.procfs- /host/proc- --path.sysfs- /host/sys- --collector.filesystem.ignored-mount-points- '"^/(sys|proc|dev|host|etc)($|/)"'volumeMounts:- name: devmountPath: /host/dev- name: procmountPath: /host/proc- name: sysmountPath: /host/sys- name: rootfsmountPath: /rootfstolerations:- key: "node-role.kubernetes.io/master"operator: "Exists"effect: "NoSchedule"volumes:- name: prochostPath:path: /proc- name: devhostPath:path: /dev- name: syshostPath:path: /sys- name: rootfshostPath:path: /
EOF

2.1、说明

  • 主机命名空间共享 (hostPID, hostIPC, hostNetwork)
    • hostPID: true: 允许 Pod 使用主机的 PID 命名空间。Pod 可以看到主机上的所有进程
    • hostIPC: true: 允许 Pod 使用主机的 IPC 命名空间。Pod 可以与其他在主机上运行的进程共享 IPC 资源(如信号量、消息队列等)。
    • hostNetwork: true: 允许 Pod 使用主机的网络命名空间。Pod 将使用主机的网络接口
  • 命令行参数 (args)
  • --path.procfs /host/proc: 指定 node-exporter 应该从 /host/proc 路径读取进程文件系统的数据。这使得 node-exporter 可以访问宿主机的进程信息。
  • --path.sysfs /host/sys: 指定 node-exporter 应该从 /host/sys 路径读取系统文件系统的数据。这使得 node-exporter 可以访问宿主机的系统信息。
  • --collector.filesystem.ignored-mount-points "^/(sys|proc|dev|host|etc)($|/)": 指定哪些文件系统的挂载点应该被忽略,不被 node-exporter 收集。这里忽略了 /sys, /proc, /dev, /host, 和 /etc 这些挂载点,避免收集不必要的数据。
  • 挂载点 (volumeMountsvolumes)
    • /proc 挂载
      • 宿主机路径: /proc
      • 容器内路径: /host/proc
      • 作用:node-exporter 访问宿主机的进程文件系统。
    • /dev 挂载
      • 宿主机路径: /dev
      • 容器内路径: /host/dev
      • 作用:node-exporter 访问宿主机的设备文件。
    • /sys 挂载
      • 宿主机路径: /sys
      • 容器内路径: /host/sys
      • 作用:node-exporter 访问宿主机的系统文件系统。
    • / 挂载
      • 宿主机路径: /
      • 容器内路径: /rootfs
      • 作用:node-exporter 访问宿主机的根文件系统。
  • 容忍度 (tolerations)
    • key: "node-role.kubernetes.io/master": 指定容忍的污点键。
    • operator: "Exists": 表示只要存在该污点键,无论值是什么,都予以容忍。
    • effect: "NoSchedule": 表示即使节点上有这种污点,也不会阻止 Pod 被调度到该节点上。

2.2、应用资源清单

kubectl apply -f node-export.yamlkubectl get pods -n monitor-sa -l name=node-exporter

image-20241005214533113

2.3、通过node-exporter采集数据

node-export默认的监听端口是9100,可以看到当前主机获取到的所有监控数据

# curl http://<master-ip>:9100/metricscurl http://192.168.112.10:9100/metrics

image-20241005214626996

3、k8s 集群中部署 prometheus

3.1、创建一个 sa 账号

kubectl create serviceaccount monitor -n monitor-sa

3.2、将 sa 账号 monitor 通过 clusterrolebing 绑定到 clusterrole 上

kubectl create clusterrolebinding monitor-clusterrolebinding -n monitor-sa --clusterrole=cluster-admin  --serviceaccount=monitor-sa:monitor

3.3、创建数据目录

所有 node 节点

mkdir /data && chmod 777 /data/

3.4、安装prometheus

master 节点操作

3.4.1、将 prometheus.yml 文件以 ConfigMap 的形式进行管理

cat  >> prometheus-cfg.yaml << 'EOF'
---
kind: ConfigMap
apiVersion: v1
metadata:labels:app: prometheusname: prometheus-confignamespace: monitor-sa
data:prometheus.yml: |global:scrape_interval: 15sscrape_timeout: 10sevaluation_interval: 1mscrape_configs:- job_name: 'kubernetes-node'kubernetes_sd_configs:- role: noderelabel_configs:- source_labels: [__address__]regex: '(.*):10250'replacement: '${1}:9100'target_label: __address__action: replace- action: labelmapregex: __meta_kubernetes_node_label_(.+)- job_name: 'kubernetes-node-cadvisor'kubernetes_sd_configs:- role:  nodescheme: httpstls_config:ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crtbearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/tokenrelabel_configs:- action: labelmapregex: __meta_kubernetes_node_label_(.+)- target_label: __address__replacement: kubernetes.default.svc:443- source_labels: [__meta_kubernetes_node_name]regex: (.+)target_label: __metrics_path__replacement: '/api/v1/nodes/${1}/proxy/metrics/cadvisor'- job_name: 'kubernetes-apiserver'kubernetes_sd_configs:- role: endpointsscheme: httpstls_config:ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crtbearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/tokenrelabel_configs:- source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]action: keepregex: default;kubernetes;https- job_name: 'kubernetes-service-endpoints'kubernetes_sd_configs:- role: endpointsrelabel_configs:- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape]action: keepregex: true- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme]action: replacetarget_label: __scheme__regex: (https?)- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path]action: replacetarget_label: __metrics_path__regex: (.+)- source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port]action: replacetarget_label: __address__regex: ([^:]+)(?::\d+)?;(\d+)replacement: '$1:$2'- action: labelmapregex: __meta_kubernetes_service_label_(.+)- source_labels: [__meta_kubernetes_namespace]action: replacetarget_label: kubernetes_namespace- source_labels: [__meta_kubernetes_service_name]action: replacetarget_label: kubernetes_name 
EOF

3.4.2、应用 cm 资源清单

kubectl apply -f prometheus-cfg.yamlkubectl get cm prometheus-config -n monitor-sa -o yaml

需要确保 cm 正确解析了变量 $1、$2

不然 prometheus 获取不到对应的 IP 地址会无法正常监控

image-20241005215107744

3.4.3、通过 Deployment 部署 prometheus

cat >> prometheus-deploy.yaml << EOF
---
apiVersion: apps/v1
kind: Deployment
metadata:name: prometheus-servernamespace: monitor-salabels:app: prometheus
spec:replicas: 2selector:matchLabels:app: prometheuscomponent: server#matchExpressions:#- {key: app, operator: In, values: [prometheus]}#- {key: component, operator: In, values: [server]}template:metadata:labels:app: prometheuscomponent: serverannotations:prometheus.io/scrape: 'false'spec:affinity:podAntiAffinity:requiredDuringSchedulingIgnoredDuringExecution:- labelSelector:matchExpressions:- key: appoperator: Invalues:- prometheus- key: componentoperator: Invalues:- servertopologyKey: kubernetes.io/hostnameserviceAccountName: monitorcontainers:- name: prometheusimage: quay.io/prometheus/prometheus:latestimagePullPolicy: IfNotPresentcommand:- prometheus- --config.file=/etc/prometheus/prometheus.yml- --storage.tsdb.path=/prometheus- --storage.tsdb.retention=720hports:- containerPort: 9090protocol: TCPvolumeMounts:- mountPath: /etc/prometheus/prometheus.ymlname: prometheus-configsubPath: prometheus.yml- mountPath: /prometheus/name: prometheus-storage-volumevolumes:- name: prometheus-configconfigMap:name: prometheus-configitems:- key: prometheus.ymlpath: prometheus.ymlmode: 0644- name: prometheus-storage-volumehostPath:path: /datatype: Directory
EOF

3.4.4、应用 prometheus 资源清单

kubectl apply -f prometheus-deploy.yaml

image-20241005215357542

3.4.5、给 prometheus 的 pod 创建一个 svc

cat  > prometheus-svc.yaml << EOF
---
apiVersion: v1
kind: Service
metadata:name: prometheusnamespace: monitor-salabels:app: prometheus
spec:type: NodePortports:- port: 9090targetPort: 9090protocol: TCPselector:app: prometheuscomponent: server
EOF

3.4.6、应用 svc 资源清单

kubectl get svc -n monitor-sa -o wide

image-20241005215425028

通过上面可以看到service在宿主机上映射的端口是30172,这样我们访问k8s集群的k8s-master1节点的ip:30172,就可以访问到prometheus的web ui界面了

3.5、访问prometheus UI界面

# <k8s-master1 IP>:32032
192.168.112.10:32032

image-20241005215529171

3.6、查看配置的服务发现

点击页面的Status->Targets,可看到如下,说明我们配置的服务发现可以正常采集数据

image-20241005221024862

4、prometheus热更新

4.1、热加载 prometheus

#为了每次修改配置文件可以热加载prometheus,也就是不停止prometheus,就可以使配置生效,如修改prometheus-cfg.yaml,想要使配置生效可用如下热加载命令:

curl -X POST http://<prometheus-pod-ip>:9090/-/reload
kubectl get pods -n monitor-sa -l app=prometheus -o wide

image-20241005221822766

4.2、暴力重启 prometheus

热加载速度比较慢,可以暴力重启prometheus

如修改上面的prometheus-cfg.yaml文件之后,可执行如下强制删除

kubectl delete -f prometheus-cfg.yamlkubectl delete -f prometheus-deploy.yaml# 然后再通过apply更新kubectl apply -f prometheus-cfg.yamlkubectl apply -f prometheus-deploy.yaml

线上最好热加载,暴力删除可能造成监控数据的丢失

5、Grafana安装和配置

5.1、下载 Grafana 需要的镜像

链接:https://pan.baidu.com/s/1TmVGKxde_cEYrbjiETboEA 
提取码:052u

5.2、在 k8s 集群各个节点导入 Grafana 镜像

docker load -i heapster-grafana-amd64_v5_0_4.tar.gzdocker images | grep grafana

image-20241005231752018

image-20241005231829736

image-20241005231844131

5.3、master 节点创建 grafana.yaml

cat >> grafana.yaml << EOF
apiVersion: apps/v1
kind: Deployment
metadata:name: monitoring-grafananamespace: kube-system
spec:replicas: 1selector:matchLabels:task: monitoringk8s-app: grafanatemplate:metadata:labels:task: monitoringk8s-app: grafanaspec:containers:- name: grafanaimage: k8s.gcr.io/heapster-grafana-amd64:v5.0.4ports:- containerPort: 3000protocol: TCPvolumeMounts:- mountPath: /etc/ssl/certsname: ca-certificatesreadOnly: true- mountPath: /varname: grafana-storageenv:- name: INFLUXDB_HOSTvalue: monitoring-influxdb- name: GF_SERVER_HTTP_PORTvalue: "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_ENABLEDvalue: "false"- name: GF_AUTH_ANONYMOUS_ENABLEDvalue: "true"- name: GF_AUTH_ANONYMOUS_ORG_ROLEvalue: 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/proxyvalue: /volumes:- name: ca-certificateshostPath:path: /etc/ssl/certs- name: grafana-storageemptyDir: {}
---
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-grafananame: monitoring-grafananamespace: 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: NodePortports:- port: 80targetPort: 3000selector:k8s-app: grafanatype: NodePort
EOF

5.4、查看 Grafana 的 pod 和 svc

image-20241005232832195

5.5、查看 Grafana UI 界面

# <master-ip>:<grafana-svc-port>192.168.112.10:31455

image-20241006150242320

5.6、给 Grafana 接入 Prometheus 数据源

选择 Create your first data source
image-20241006150534861
image-20241006150624325
Name: Prometheus |Type: Prometheus|HTTP 处的URL写 如下:http://prometheus.monitor-sa.svc:9090
image-20241006151022903
点击左下角 Save & Test,出现如下 Data source is working,说明 prometheus 数据源成功的被 grafana 接入了
image-20241006151134680
image-20241006151148648

5.7、获取监控模板

  • 可以在 Grafana Dashboard 官网搜索需要的

Grafana dashboards | Grafana Labs

  • 也可以直接克隆 Github 仓库,获取 node_exporter.json 、 docker_rev1.json 监控模板
git clone git@github.com:misakivv/Grafana-Dashboard.git

5.8、导入监控模板

依次点击左侧栏的 + 号下方的 Import
image-20241006152716109
选择 Upload json file,选择一个本地的node_exporter.json 文件
image-20241006153035574
导入后 Options 选项中会出现 Name 是自动生成的,Prometheus 是需要我们选择 Prometheus的
image-20241006153231878
点击 Import 即可出现如下界面
image-20241006153455006
按照如上操作,导入docker_rev1.json监控模板
image-20241006153635176
image-20241006153710723

6、安装配置 kube-state-metrics 组件

6.1、什么是 kube-state-metrics

kube-state-metrics通过监听API Server生成有关资源对象的状态指标,比如Deployment、Node、Pod,需要注意的是kube-state-metrics只是简单的提供一个metrics数据,并不会存储这些指标数据,所以我们可以使用Prometheus来抓取这些数据然后存储,主要关注的是业务相关的一些元数据,比如Deployment、Pod、副本状态等;调度了多少个replicas?现在可用的有几个?多少个Pod是running/stopped/terminated状态?Pod重启了多少次?有多少job在运行中。

6.2、创建 sa ,并进行授权

k8s-master1 节点编写一个 kube-state-metrics-rbac.yaml 文件

cat >> kube-state-metrics-rbac.yaml << EOF
---
apiVersion: v1
kind: ServiceAccount
metadata:name: kube-state-metricsnamespace: 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.iokind: ClusterRolename: kube-state-metrics
subjects:
- kind: ServiceAccountname: kube-state-metricsnamespace: kube-system
EOF
kubectl get sa,clusterrole,clusterrolebinding -n kube-system | grep kube-state-metrics

image-20241006155708266

6.3、创建并应用 kube-state-metrics-deploy.yaml 文件

k8s-master1 节点操作

cat > kube-state-metrics-deploy.yaml <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:name: kube-state-metricsnamespace: kube-system
spec:replicas: 1selector:matchLabels:app: kube-state-metricstemplate:metadata:labels:app: kube-state-metricsspec:serviceAccountName: kube-state-metricscontainers:- name: kube-state-metrics
#        image: gcr.io/google_containers/kube-state-metrics-amd64:v1.3.1image: quay.io/coreos/kube-state-metrics:latestports:- containerPort: 8080
EOF
kubectl apply -f kube-state-metrics-deploy.yamlkubectl get pods -n kube-system -l app=kube-state-metrics -w

image-20241006162620908

拉取 kube-state-metrics 指定镜像版本失败时可以选择在集群各个节点上

docker pull quay.io/coreos/kube-state-metrics:latest

拉取最新 tag 版本

image-20241006162304963

6.4、创建并应用 kube-state-metrics-svc.yaml 文件

k8s-master1 节点操作

cat >> kube-state-metrics-svc.yaml <<EOF
apiVersion: v1
kind: Service
metadata:annotations:prometheus.io/scrape: 'true'name: kube-state-metricsnamespace: kube-systemlabels:app: kube-state-metrics
spec:ports:- name: kube-state-metricsport: 8080protocol: TCPselector:app: kube-state-metrics
EOF
kubectl apply -f kube-state-metrics-svc.yamlkubectl get svc -n kube-system -l app=kube-state-metrics

image-20241006163135415

6.5、获取 kube-state-metrics json 文件

git clone git@github.com:misakivv/Grafana-Dashboard.git

image-20241006163929057

6.6、向 Grafana 导入 kube-state-metrics json 文件

点击左侧栏 + 号的 Import
image-20241006163710887
点击 Upload .json File,上传 Kubernetes Cluster (Prometheus)-1577674936972.json
image-20241006164143527
image-20241006164305915
查看
image-20241006165042653
**同样的导入 Kubernetes cluster monitoring (via Prometheus) (k8s 1.16)-1577691996738.json **
image-20241006165253781
image-20241006165821679
image-20241006165850539
image-20241006165912093
image-20241006165931820
image-20241006165949255
image-20241006170018099
image-20241006170044368

三、安装和配置 Alertmanager -- 发送告警到 QQ 邮箱

1、将 alertmanager-cm.yaml 文件以 cm 形式进行管理

k8s-master1 节点操作

cat >> alertmanager-cm.yaml << EOF
kind: ConfigMap
apiVersion: v1
metadata:name: alertmanagernamespace: monitor-sa
data:alertmanager.yml: |-global:resolve_timeout: 1msmtp_smarthost: 'smtp.qq.com:465'smtp_from: '2830909671@qq.com'smtp_auth_username: '2830909671@qq.com'smtp_auth_password: 'ajjgpgwwfkpcdgih'smtp_require_tls: falseroute:group_by: [alertname]group_wait: 5sgroup_interval: 5srepeat_interval: 5mreceiver: default-receiverreceivers:- name: 'default-receiver'email_configs:- to: 'misakikk@qq.com'send_resolved: true
EOF
kubectl apply -f alertmanager-cm.yamlkubectl get cm alertmanager -n monitor-sa

image-20241006174637564

1.1、alertmanager配置文件说明

smtp_smarthost: 'smtp.qq.com:465'
#用于发送邮件的邮箱的SMTP服务器地址+端口。QQ 邮箱 SMTP 服务地址,官方地址为 smtp.qq.com 端口为 465 或 587,同时要设置开启 POP3/SMTP 服务。
smtp_from: '2830909671@qq.com'
#这是指定从哪个邮箱发送报警
smtp_auth_password: 'ajjgpgwwfkpcdgih'
#这是发送邮箱的授权码而不是登录密码
email_configs:- to: 'misakikk@qq.com'
#to后面指定发送到哪个邮箱

2、重新生成并应用 prometheus-cfg.yaml 文件

k8s-master1 节点操作

cat > prometheus-cfg.yaml << 'EOF'
kind: ConfigMap
apiVersion: v1
metadata:labels:app: prometheusname: prometheus-confignamespace: monitor-sa
data:prometheus.yml: |rule_files:- /etc/prometheus/rules.ymlalerting:alertmanagers:- static_configs:- targets: ["localhost:9093"]global:scrape_interval: 15sscrape_timeout: 10sevaluation_interval: 1mscrape_configs:- job_name: 'kubernetes-node'kubernetes_sd_configs:- role: noderelabel_configs:- source_labels: [__address__]regex: '(.*):10250'replacement: '${1}:9100'target_label: __address__action: replace- action: labelmapregex: __meta_kubernetes_node_label_(.+)- job_name: 'kubernetes-node-cadvisor'kubernetes_sd_configs:- role:  nodescheme: httpstls_config:ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crtbearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/tokenrelabel_configs:- action: labelmapregex: __meta_kubernetes_node_label_(.+)- target_label: __address__replacement: kubernetes.default.svc:443- source_labels: [__meta_kubernetes_node_name]regex: (.+)target_label: __metrics_path__replacement: '/api/v1/nodes/${1}/proxy/metrics/cadvisor'- job_name: 'kubernetes-apiserver'kubernetes_sd_configs:- role: endpointsscheme: httpstls_config:ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crtbearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/tokenrelabel_configs:- source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]action: keepregex: default;kubernetes;https- job_name: 'kubernetes-service-endpoints'kubernetes_sd_configs:- role: endpointsrelabel_configs:- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape]action: keepregex: true- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme]action: replacetarget_label: __scheme__regex: (https?)- source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path]action: replacetarget_label: __metrics_path__regex: (.+)- source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port]action: replacetarget_label: __address__regex: ([^:]+)(?::\d+)?;(\d+)replacement: '$1:$2'- action: labelmapregex: __meta_kubernetes_service_label_(.+)- source_labels: [__meta_kubernetes_namespace]action: replacetarget_label: kubernetes_namespace- source_labels: [__meta_kubernetes_service_name]action: replacetarget_label: kubernetes_name - job_name: 'kubernetes-pods'kubernetes_sd_configs:- role: podrelabel_configs:- action: keepregex: truesource_labels:- __meta_kubernetes_pod_annotation_prometheus_io_scrape- action: replaceregex: (.+)source_labels:- __meta_kubernetes_pod_annotation_prometheus_io_pathtarget_label: __metrics_path__- action: replaceregex: ([^:]+)(?::\d+)?;(\d+)replacement: '$1:$2'source_labels:- __address__- __meta_kubernetes_pod_annotation_prometheus_io_porttarget_label: __address__- action: labelmapregex: __meta_kubernetes_pod_label_(.+)- action: replacesource_labels:- __meta_kubernetes_namespacetarget_label: kubernetes_namespace- action: replacesource_labels:- __meta_kubernetes_pod_nametarget_label: kubernetes_pod_name- job_name: 'kubernetes-schedule'scrape_interval: 5sstatic_configs:- targets: ['192.168.112.10:10259']- job_name: 'kubernetes-controller-manager'scrape_interval: 5sstatic_configs:- targets: ['192.168.112.10:10257']- job_name: 'kubernetes-kube-proxy'scrape_interval: 5sstatic_configs:- targets: ['192.168.112.10:10249','192.168.112.20:10249','192.168.112.30:10249']- job_name: 'kubernetes-etcd'scheme: httpstls_config:ca_file: /var/run/secrets/kubernetes.io/k8s-certs/etcd/ca.crtcert_file: /var/run/secrets/kubernetes.io/k8s-certs/etcd/server.crtkey_file: /var/run/secrets/kubernetes.io/k8s-certs/etcd/server.keyscrape_interval: 5sstatic_configs:- targets: ['192.168.112.10:2381']rules.yml: |groups:- name: examplerules:- alert: kube-proxy的cpu使用率大于80%expr: rate(process_cpu_seconds_total{job=~"kubernetes-kube-proxy"}[1m]) * 100 > 80for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过80%"- alert:  kube-proxy的cpu使用率大于90%expr: rate(process_cpu_seconds_total{job=~"kubernetes-kube-proxy"}[1m]) * 100 > 90for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过90%"- alert: scheduler的cpu使用率大于80%expr: rate(process_cpu_seconds_total{job=~"kubernetes-schedule"}[1m]) * 100 > 80for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过80%"- alert:  scheduler的cpu使用率大于90%expr: rate(process_cpu_seconds_total{job=~"kubernetes-schedule"}[1m]) * 100 > 90for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过90%"- alert: controller-manager的cpu使用率大于80%expr: rate(process_cpu_seconds_total{job=~"kubernetes-controller-manager"}[1m]) * 100 > 80for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过80%"- alert:  controller-manager的cpu使用率大于90%expr: rate(process_cpu_seconds_total{job=~"kubernetes-controller-manager"}[1m]) * 100 > 0for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过90%"- alert: apiserver的cpu使用率大于80%expr: rate(process_cpu_seconds_total{job=~"kubernetes-apiserver"}[1m]) * 100 > 80for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过80%"- alert:  apiserver的cpu使用率大于90%expr: rate(process_cpu_seconds_total{job=~"kubernetes-apiserver"}[1m]) * 100 > 90for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过90%"- alert: etcd的cpu使用率大于80%expr: rate(process_cpu_seconds_total{job=~"kubernetes-etcd"}[1m]) * 100 > 80for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过80%"- alert:  etcd的cpu使用率大于90%expr: rate(process_cpu_seconds_total{job=~"kubernetes-etcd"}[1m]) * 100 > 90for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}组件的cpu使用率超过90%"- alert: kube-state-metrics的cpu使用率大于80%expr: rate(process_cpu_seconds_total{k8s_app=~"kube-state-metrics"}[1m]) * 100 > 80for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.k8s_app}}组件的cpu使用率超过80%"value: "{{ $value }}%"threshold: "80%"      - alert: kube-state-metrics的cpu使用率大于90%expr: rate(process_cpu_seconds_total{k8s_app=~"kube-state-metrics"}[1m]) * 100 > 0for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.k8s_app}}组件的cpu使用率超过90%"value: "{{ $value }}%"threshold: "90%"      - alert: coredns的cpu使用率大于80%expr: rate(process_cpu_seconds_total{k8s_app=~"kube-dns"}[1m]) * 100 > 80for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.k8s_app}}组件的cpu使用率超过80%"value: "{{ $value }}%"threshold: "80%"      - alert: coredns的cpu使用率大于90%expr: rate(process_cpu_seconds_total{k8s_app=~"kube-dns"}[1m]) * 100 > 90for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.k8s_app}}组件的cpu使用率超过90%"value: "{{ $value }}%"threshold: "90%"      - alert: kube-proxy打开句柄数>600expr: process_open_fds{job=~"kubernetes-kube-proxy"}  > 600for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>600"value: "{{ $value }}"- alert: kube-proxy打开句柄数>1000expr: process_open_fds{job=~"kubernetes-kube-proxy"}  > 1000for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>1000"value: "{{ $value }}"- alert: kubernetes-schedule打开句柄数>600expr: process_open_fds{job=~"kubernetes-schedule"}  > 600for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>600"value: "{{ $value }}"- alert: kubernetes-schedule打开句柄数>1000expr: process_open_fds{job=~"kubernetes-schedule"}  > 1000for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>1000"value: "{{ $value }}"- alert: kubernetes-controller-manager打开句柄数>600expr: process_open_fds{job=~"kubernetes-controller-manager"}  > 600for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>600"value: "{{ $value }}"- alert: kubernetes-controller-manager打开句柄数>1000expr: process_open_fds{job=~"kubernetes-controller-manager"}  > 1000for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>1000"value: "{{ $value }}"- alert: kubernetes-apiserver打开句柄数>600expr: process_open_fds{job=~"kubernetes-apiserver"}  > 600for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>600"value: "{{ $value }}"- alert: kubernetes-apiserver打开句柄数>1000expr: process_open_fds{job=~"kubernetes-apiserver"}  > 1000for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>1000"value: "{{ $value }}"- alert: kubernetes-etcd打开句柄数>600expr: process_open_fds{job=~"kubernetes-etcd"}  > 600for: 2slabels:severity: warnningannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>600"value: "{{ $value }}"- alert: kubernetes-etcd打开句柄数>1000expr: process_open_fds{job=~"kubernetes-etcd"}  > 1000for: 2slabels:severity: criticalannotations:description: "{{$labels.instance}}的{{$labels.job}}打开句柄数>1000"value: "{{ $value }}"- alert: corednsexpr: process_open_fds{k8s_app=~"kube-dns"}  > 600for: 2slabels:severity: warnning annotations:description: "插件{{$labels.k8s_app}}({{$labels.instance}}): 打开句柄数超过600"value: "{{ $value }}"- alert: corednsexpr: process_open_fds{k8s_app=~"kube-dns"}  > 1000for: 2slabels:severity: criticalannotations:description: "插件{{$labels.k8s_app}}({{$labels.instance}}): 打开句柄数超过1000"value: "{{ $value }}"- alert: kube-proxyexpr: process_virtual_memory_bytes{job=~"kubernetes-kube-proxy"}  > 2000000000for: 2slabels:severity: warnningannotations:description: "组件{{$labels.job}}({{$labels.instance}}): 使用虚拟内存超过2G"value: "{{ $value }}"- alert: schedulerexpr: process_virtual_memory_bytes{job=~"kubernetes-schedule"}  > 2000000000for: 2slabels:severity: warnningannotations:description: "组件{{$labels.job}}({{$labels.instance}}): 使用虚拟内存超过2G"value: "{{ $value }}"- alert: kubernetes-controller-managerexpr: process_virtual_memory_bytes{job=~"kubernetes-controller-manager"}  > 2000000000for: 2slabels:severity: warnningannotations:description: "组件{{$labels.job}}({{$labels.instance}}): 使用虚拟内存超过2G"value: "{{ $value }}"- alert: kubernetes-apiserverexpr: process_virtual_memory_bytes{job=~"kubernetes-apiserver"}  > 2000000000for: 2slabels:severity: warnningannotations:description: "组件{{$labels.job}}({{$labels.instance}}): 使用虚拟内存超过2G"value: "{{ $value }}"- alert: kubernetes-etcdexpr: process_virtual_memory_bytes{job=~"kubernetes-etcd"}  > 2000000000for: 2slabels:severity: warnningannotations:description: "组件{{$labels.job}}({{$labels.instance}}): 使用虚拟内存超过2G"value: "{{ $value }}"- alert: kube-dnsexpr: process_virtual_memory_bytes{k8s_app=~"kube-dns"}  > 2000000000for: 2slabels:severity: warnningannotations:description: "插件{{$labels.k8s_app}}({{$labels.instance}}): 使用虚拟内存超过2G"value: "{{ $value }}"- alert: HttpRequestsAvgexpr: sum(rate(rest_client_requests_total{job=~"kubernetes-kube-proxy|kubernetes-kubelet|kubernetes-schedule|kubernetes-control-manager|kubernetes-apiservers"}[1m]))  > 1000for: 2slabels:team: adminannotations:description: "组件{{$labels.job}}({{$labels.instance}}): TPS超过1000"value: "{{ $value }}"threshold: "1000"   - alert: Pod_restartsexpr: kube_pod_container_status_restarts_total{namespace=~"kube-system|default|monitor-sa"} > 0for: 2slabels:severity: warnningannotations:description: "在{{$labels.namespace}}名称空间下发现{{$labels.pod}}这个pod下的容器{{$labels.container}}被重启,这个监控指标是由{{$labels.instance}}采集的"value: "{{ $value }}"threshold: "0"- alert: Pod_waitingexpr: kube_pod_container_status_waiting_reason{namespace=~"kube-system|default"} == 1for: 2slabels:team: adminannotations:description: "空间{{$labels.namespace}}({{$labels.instance}}): 发现{{$labels.pod}}下的{{$labels.container}}启动异常等待中"value: "{{ $value }}"threshold: "1"   - alert: Pod_terminatedexpr: kube_pod_container_status_terminated_reason{namespace=~"kube-system|default|monitor-sa"} == 1for: 2slabels:team: adminannotations:description: "空间{{$labels.namespace}}({{$labels.instance}}): 发现{{$labels.pod}}下的{{$labels.container}}被删除"value: "{{ $value }}"threshold: "1"- alert: Etcd_leaderexpr: etcd_server_has_leader{job="kubernetes-etcd"} == 0for: 2slabels:team: adminannotations:description: "组件{{$labels.job}}({{$labels.instance}}): 当前没有leader"value: "{{ $value }}"threshold: "0"- alert: Etcd_leader_changesexpr: rate(etcd_server_leader_changes_seen_total{job="kubernetes-etcd"}[1m]) > 0for: 2slabels:team: adminannotations:description: "组件{{$labels.job}}({{$labels.instance}}): 当前leader已发生改变"value: "{{ $value }}"threshold: "0"- alert: Etcd_failedexpr: rate(etcd_server_proposals_failed_total{job="kubernetes-etcd"}[1m]) > 0for: 2slabels:team: adminannotations:description: "组件{{$labels.job}}({{$labels.instance}}): 服务失败"value: "{{ $value }}"threshold: "0"- alert: Etcd_db_total_sizeexpr: etcd_debugging_mvcc_db_total_size_in_bytes{job="kubernetes-etcd"} > 10000000000for: 2slabels:team: adminannotations:description: "组件{{$labels.job}}({{$labels.instance}}):db空间超过10G"value: "{{ $value }}"threshold: "10G"- alert: Endpoint_readyexpr: kube_endpoint_address_not_ready{namespace=~"kube-system|default"} == 1for: 2slabels:team: adminannotations:description: "空间{{$labels.namespace}}({{$labels.instance}}): 发现{{$labels.endpoint}}不可用"value: "{{ $value }}"threshold: "1"- name: 物理节点状态-监控告警rules:- alert: 物理节点cpu使用率expr: 100-avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by(instance)*100 > 90for: 2slabels:severity: ccriticalannotations:summary: "{{ $labels.instance }}cpu使用率过高"description: "{{ $labels.instance }}的cpu使用率超过90%,当前使用率[{{ $value }}],需要排查处理" - alert: 物理节点内存使用率expr: (node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) / node_memory_MemTotal_bytes * 100 > 90for: 2slabels:severity: criticalannotations:summary: "{{ $labels.instance }}内存使用率过高"description: "{{ $labels.instance }}的内存使用率超过90%,当前使用率[{{ $value }}],需要排查处理"- alert: InstanceDownexpr: up == 0for: 2slabels:severity: criticalannotations:   summary: "{{ $labels.instance }}: 服务器宕机"description: "{{ $labels.instance }}: 服务器延时超过2分钟"- alert: 物理节点磁盘的IO性能expr: 100-(avg(irate(node_disk_io_time_seconds_total[1m])) by(instance)* 100) < 60for: 2slabels:severity: criticalannotations:summary: "{{$labels.mountpoint}} 流入磁盘IO使用率过高!"description: "{{$labels.mountpoint }} 流入磁盘IO大于60%(目前使用:{{$value}})"- alert: 入网流量带宽expr: ((sum(rate (node_network_receive_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*'}[5m])) by (instance)) / 100) > 102400for: 2slabels:severity: criticalannotations:summary: "{{$labels.mountpoint}} 流入网络带宽过高!"description: "{{$labels.mountpoint }}流入网络带宽持续5分钟高于100M. RX带宽使用率{{$value}}"- alert: 出网流量带宽expr: ((sum(rate (node_network_transmit_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*'}[5m])) by (instance)) / 100) > 102400for: 2slabels:severity: criticalannotations:summary: "{{$labels.mountpoint}} 流出网络带宽过高!"description: "{{$labels.mountpoint }}流出网络带宽持续5分钟高于100M. RX带宽使用率{{$value}}"- alert: TCP会话expr: node_netstat_Tcp_CurrEstab > 1000for: 2slabels:severity: criticalannotations:summary: "{{$labels.mountpoint}} TCP_ESTABLISHED过高!"description: "{{$labels.mountpoint }} TCP_ESTABLISHED大于1000%(目前使用:{{$value}}%)"- alert: 磁盘容量expr: 100-(node_filesystem_free_bytes{fstype=~"ext4|xfs"}/node_filesystem_size_bytes {fstype=~"ext4|xfs"}*100) > 80for: 2slabels:severity: criticalannotations:summary: "{{$labels.mountpoint}} 磁盘分区使用率过高!"description: "{{$labels.mountpoint }} 磁盘分区使用大于80%(目前使用:{{$value}}%)"
EOF

注意:

除了kube-proxy 默认在每个节点的 10249 端口上暴露其指标

其余的 kubernetes-schedulekubernetes-controller-managerkubernetes-etcd 这些组件Pod 的容器需要根据自己的 k8s 集群情况进行修改

kubectl apply -f prometheus-cfg.yamlkubectl get cm prometheus-config -n monitor-sa -o yaml

同样的还是需要检查 cm 文件中是否正确解析了 $1 $2

image-20241006191724613

3、重新生成 prometheus-deploy.yaml 文件

k8s-master1 节点操作

cat > prometheus-deploy.yaml << EOF
---
apiVersion: apps/v1
kind: Deployment
metadata:name: prometheus-servernamespace: monitor-salabels:app: prometheus
spec:replicas: 2selector:matchLabels:app: prometheuscomponent: server#matchExpressions:#- {key: app, operator: In, values: [prometheus]}#- {key: component, operator: In, values: [server]}template:metadata:labels:app: prometheuscomponent: serverannotations:prometheus.io/scrape: 'false'spec:affinity:podAntiAffinity:requiredDuringSchedulingIgnoredDuringExecution:- labelSelector:matchExpressions:- key: appoperator: Invalues:- prometheus- key: componentoperator: Invalues:- servertopologyKey: kubernetes.io/hostnameserviceAccountName: monitorcontainers:- name: prometheusimage: quay.io/prometheus/prometheus:latestimagePullPolicy: IfNotPresentcommand:- "/bin/prometheus"args:- "--config.file=/etc/prometheus/prometheus.yml"- "--storage.tsdb.path=/prometheus"- "--storage.tsdb.retention=24h"- "--web.enable-lifecycle"ports:- containerPort: 9090protocol: TCPvolumeMounts:- mountPath: /etc/prometheusname: prometheus-config- mountPath: /prometheus/name: prometheus-storage-volume- name: k8s-certsmountPath: /var/run/secrets/kubernetes.io/k8s-certs/etcd/- name: alertmanagerimage: prom/alertmanager:latestimagePullPolicy: IfNotPresentargs:- "--config.file=/etc/alertmanager/alertmanager.yml"- "--log.level=debug"ports:- containerPort: 9093protocol: TCPname: alertmanagervolumeMounts:- name: alertmanager-configmountPath: /etc/alertmanager- name: alertmanager-storagemountPath: /alertmanager- name: localtimemountPath: /etc/localtimevolumes:- name: prometheus-configconfigMap:name: prometheus-config- name: prometheus-storage-volumehostPath:path: /datatype: Directory- name: k8s-certssecret:secretName: etcd-certs- name: alertmanager-configconfigMap:name: alertmanager- name: alertmanager-storagehostPath:path: /data/alertmanagertype: DirectoryOrCreate- name: localtimehostPath:path: /usr/share/zoneinfo/Asia/Shanghai
EOF

3.1、创建一个名为 etcd-certs 的 Secret

kubectl -n monitor-sa create secret generic etcd-certs --from-file=/etc/kubernetes/pki/etcd/server.key  --from-file=/etc/kubernetes/pki/etcd/server.crt --from-file=/etc/kubernetes/pki/etcd/ca.crt

image-20241006194149381

3.2、应用 prometheus-deploy.yaml 文件

kubectl apply -f prometheus-deploy.yamlkubectl get pods -n monitor-sa

image-20241006211236948

4、重新生成并创建 alertmanager-svc.yaml 文件

cat >alertmanager-svc.yaml <<EOF
---
apiVersion: v1
kind: Service
metadata:labels:name: prometheuskubernetes.io/cluster-service: 'true'name: alertmanagernamespace: monitor-sa
spec:ports:- name: alertmanagernodePort: 30066port: 9093protocol: TCPtargetPort: 9093selector:app: prometheussessionAffinity: Nonetype: NodePort
EOF
kubectl apply -f alertmanager-svc.yamlkubectl get svc alertmanager -n monitor-sa

image-20241006211627124

5、访问 prometheus UI 界面

image-20241007102819517

5.1、【error】kube-controller-manager、etcd、kube-proxy、kube-scheduler 组件 connection refused

5.1.1、kube-proxy

默认情况下,该服务监听端口只提供给127.0.0.1,需修改为0.0.0.0

 kubectl edit cm/kube-proxy -n kube-system
  • 编辑文件,将文件修改允许0.0.0.0即可,保存
    metricsBindAddress: 0.0.0.0:10249

image-20241007121231980

  • 删除重建 kube-proxy 的 pod
kubectl delete pod -l k8s-app=kube-proxy -n kube-system

image-20241007121419636

  • 效果

image-20241007121111763

5.1.2、kube-controller-manager

事先说明:到这一步我试过网上很多方法都没有成功获取到数据,所以我重新创建了 sa 慎用,仅供参考

  • 修改 kube-controller-manager 的 yaml 文件

默认监听本地修改为 0.0.0.0

- --bind-address=127.0.0.1
# 修改为
- --bind-address=0.0.0.0
  • 创建ServiceAccount

创建一个新的ServiceAccount,用于Prometheus访问 kube-controller-manager

cat > prom-sa << EOF
apiVersion: v1
kind: ServiceAccount
metadata:name: prometheus-sanamespace: monitor-sa
EOF
  • 创建ClusterRole

创建一个ClusterRole,定义Prometheus所需的权限。

cat > porm-role << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:name: prometheus-role
rules:
- nonResourceURLs:- "/metrics"verbs:- get
EOF
  • 创建ClusterRoleBinding

将ServiceAccount绑定到ClusterRole。

cat > prom-bind.yaml << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:name: prometheus-binding
subjects:
- kind: ServiceAccountname: prometheus-sanamespace: monitor-sa
roleRef:kind: ClusterRolename: prometheus-roleapiGroup: rbac.authorization.k8s.io
EOF
  • 获取ServiceAccount的Token

获取ServiceAccount的Token,以便在Prometheus配置中使用。

TOKEN=$(kubectl get secret $(kubectl get sa prometheus-sa -n monitor-sa -o json | jq -r '.secrets[].name') -n monitor-sa -o json | jq -r '.data.token' | base64 --decode)
  • 修改Prometheus配置文件(cm)
- job_name: 'kubernetes-controller-manager'scheme: httpstls_config:insecure_skip_verify: true  # 禁用证书验证authorization:credentials: eyJhbGciOiJSUzI1NiIsImtpZCI6IkFEWVNqaWlueWVDMzBUcTZvQk9MRkpxQ0diLWRGWkNoaWlpZkgwR21NcEkifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJtb25pdG9yLXNhIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6InByb21ldGhldXMtc2EtdG9rZW4tbnQ5bm4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoicHJvbWV0aGV1cy1zYSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjQ4YTA5NDExLTAwMmYtNDE0Ni05YzY4LTBiNmVjOWYzYWZlZCIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDptb25pdG9yLXNhOnByb21ldGhldXMtc2EifQ.DNgCjTVxsrGDltvQZG-x7qPQrh369SO_e0faGrrhjgkBLS4q2sh85wkaBNNZcIjxZcVk7ZU9gQmQkM3AIgGIcIURpQGDMgVVI_xF1JV8iQWe-nL1yHnQAXDjyMAd1826wVvMH8LSKqdKfPVaMHN8t0LScX5yHonSJUqoevxi7Mm7tiUd33IlMQ6xH6M8Tu8bsg-fOVmL6nnGpC1tPgaZy8M_GA_Kh9j8SwHXi4Yd9r75eOSa3J6N4KF6n-EPKxnGmXDooA60G94YptsDFCQMi1t4TLAFR1FKraycWHwPbIwviUZTvA1WXbkiHnh0R6q-y0hHJVbAi_ZXagVXKZFBaw  # 替换为实际的Token值scrape_interval: 5sstatic_configs:- targets: ['192.168.112.10:10257']
  • 重启Prometheus

更新配置后,重启Prometheus以应用新的配置。

kubectl rollout restart deployment/prometheus-server -n monitor-sa
  • 效果

image-20241007173313086

5.1.3、kube-schedule

和 kube-controller-manager 操作一致

  • 效果

image-20241007174612964

5.1.4、etcd

  • 修改创建 etcd 的 yaml 文件

添加 master 节点 ip + etcd port

vim /etc/kubernetes/manifests/etcd.yaml- --listen-metrics-urls=http://127.0.0.1:2381,http://192.168.112.10:2381

image-20241007175408503

  • 修改 prometheus.yaml 文件
改为 http

image-20241007175613604

  • 效果

image-20241007175150365

6、点击Alerts,查看

image-20241007175925889

7、把controller-manager的cpu使用率大于90%展开

FIRING表示prometheus已经将告警发给alertmanager

在Alertmanager 中可以看到有 alert。

image-20241007180133147

8、登录 alertmanager UI

<master-ip>:svc-alertmanager-port192.168.112.10:30066

image-20241007180525364

image-20241007180341995

9、登录 QQ 邮箱查看告警信息

image-20241007180724123

四、配置 Alertmanager 报警 -- 发送告警到钉钉

1、手机端拉群

因为 PC 端不好操作

IMG_20241007_185306

2、创建自定义机器人

自定义机器人安全设置 - 钉钉开放平台 (dingtalk.com)

群设置
image-20241007185813640
机器人
image-20241007190002110
添加机器人
image-20241007190053622
自定义
image-20241007190125011
添加
image-20241007190214813
机器人名字、安全设置
image-20241007190915612
保管好 Webhook
image-20241007191221897

3、获取钉钉的 Webhook 插件

master 节点操作

git clone git@github.com:misakivv/prometheus-webhook-dingtalk.gitcd prometheus-webhook-dingtalktar zxvf prometheus-webhook-dingtalk-0.3.0.linux-amd64.tar.gzcd prometheus-webhook-dingtalk-0.3.0.linux-amd64

image-20241007192418023

4、启动钉钉告警插件

nohup ./prometheus-webhook-dingtalk --web.listen-address="0.0.0.0:8060" --ding.profile="cluster1=https://oapi.dingtalk.com/robot/send?access_token=feb3df2c6a987c8c1466c16eb90f4c2d3817c481aacf15cecc46f588f2716f25" &

image-20241007202305558

5、对 alertmanager-cm.yaml 文件做备份

cp alertmanager-cm.yaml alertmanager-cm.yaml.bak

6、重新生成新的 alertmanager-cm.yaml 文件

cat >alertmanager-cm.yaml <<EOF
kind: ConfigMap
apiVersion: v1
metadata:name: alertmanagernamespace: monitor-sa
data:alertmanager.yml: |-global:resolve_timeout: 1msmtp_smarthost: 'smtp.qq.com:465'smtp_from: '2830909671@qq.com'smtp_auth_username: '2830909671@qq.com'smtp_auth_password: 'ajjgpgwwfkpcdgih'smtp_require_tls: falseroute:group_by: [alertname]group_wait: 10sgroup_interval: 10srepeat_interval: 10mreceiver: cluster1receivers:- name: cluster1webhook_configs:- url: 'http://192.168.112.10:8060/dingtalk/cluster1/send'send_resolved: true
EOF

7、重建资源以生效

kubectl delete cm alertmanager -n monitor-sakubectl apply -f alertmanager-cm.yamlkubectl delete -f prometheus-cfg.yamlkubectl apply -f prometheus-cfg.yamlkubectl delete -f prometheus-deploy.yamlkubectl apply -f prometheus-deploy.yaml

image-20241007203234415

8、效果

image-20241007203102485
image-20241007203427726
image-20241007203454338
image-20241007203613020
image-20241007203905132
image-20241007203933639

暂时先这样,其实 alertmanager 还有静默、去重、抑制等功能,下一篇再共同学习

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/809606.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

软件工程第二次结对作业

软件工程 https://edu.cnblogs.com/campus/fzu/SE2024作业要求 https://edu.cnblogs.com/campus/fzu/SE2024/homework/13281作业目标 基于第一次结对作业项目程序的实现学号 102201127合作伙伴 102201129项目分工: 102201129周鑫: 前端开发: 设计和实现用户界面。 确保界面响…

20241007

sequence 我们会发现,我们每次删的一定是长度最短的那个,所以我们可以最开始按照长的排一下序,然后用线段树维护每一个区间中还有几个数,每次加上答案后在两个端点打上标记即可 #include <bits/stdc++.h> #define _1 (__int128)1using namespace std; using ll = long lo…

软件工程week2课程作业|“物品复活“软件开发

“物品复活”软件开发 作业要求 大学生经常有些物品觉得扔掉可惜,不处理又觉得浪费自己的地方。请你编写一个物品“复活”软件 该程序允许添加物品的信息(物品名称,物品描述,联系人信息),删除物品的信息,显示物品列表,也允许查找物品的信息 你实现的程序可以采用命令行…

[42] (多校联训) A层冲刺NOIP2024模拟赛03

今天的乐子今天的乐子2 昨天晚上做梦 梦见自己被关进戒网瘾学校 里面的老师全和疯子一样 然后我和这帮疯子老师比疯 疯子老师发现他们没我疯 所以就把我放了今天的乐子3 lhx 罗曼蒂克的辟谷A.五彩斑斓 赛时的想法 \(n^4\) 的做法,设 \(f_{i,j,k,l}\) 表示以 \((i,j)\) 为左上角…

Metasploit渗透测试框架学习(一)基本使用教程

1.Metasploit框架结构 1.1总览基础库文件Rex为最底层,实现网络套接字、网络应用协议、客户端服务端交互、数据库支持等 framework-core实现与上层模块交互的接口 framework-base对framework-core的扩展封装,用于提供各种接口供用户调用基于framework-base实现的六大模块Explo…

统计学(十三)——相关分析

img { display: block; margin-left: auto; margin-right: auto } table { margin-left: auto; margin-right: auto } 相关分析是用于研究多个变量之间相互关系的统计方法,最早由英国统计学家卡尔皮尔逊(Karl Pearson)于1896年提出。皮尔逊通过对变量间线性关系的深入研究,…

前端模块化进化史:从全局 function 到 ES Modules

目前,前端开发已经离不开由 CommonJS、ES Modules 和 Webpack 构建的模块化开发环境。无论是 JavaScript、CSS、图片还是其他资源,都可以作为一个模块来处理。那么,模块化究竟是如何发展到今天的呢? 全局函数模式 最初的前端模块化尝试是通过 全局函数来实现的。例如,在一…

CF131C题解

贪心,优先队列,CF 2200传送门:https://codeforces.com/problemset/problem/134/C 关注到题目的两个限制:1. 一个人只能与另外同一人交换一张卡牌。2. 一个人只能交换自己原来颜色的卡牌。 对于2条限制条件,显然有贪心思路:尽量让更多的人手持原有的卡牌。对于当前待交换的…

『模拟赛』多校A层冲刺NOIP2024模拟赛03

『模拟赛记录』多校A层冲刺NOIP2024模拟赛03Rank 炸了,触底反弹A. 五彩斑斓(colorful) 签,又没签上。 考虑如何一步步优化暴力。最暴力的思想 \(\mathcal{O(n^4)}\) 枚举每个矩形,判断四个顶点颜色。稍微优化些,两次 \(\mathcal{O(n^2)}\) 跑出对于行/列每个点下一个与之…

加装spark-3.5.3

集群版本 hadoop-3.4.0 hive-3.1.3 zookeeper-3.9.2 hbase-2.6.0(1.0.0以上需要zookeeper-3.4.0以上) spark-3.5.3(只能选2.13.0) scala-2.13.0(jdk8仅支持x.x.0系)总结一下:JDK8和scala-2.13.0必选。1.安装scala 1.1 下载解压 tar zxvf scala-2.13.0.tgz 1.2 配置环境变…

高级程序语言第二次个人作业

高级程序语言第二次作业这个作业属于哪个课程 https://edu.cnblogs.com/campus/fzu这个作业要求在哪里 https://edu.cnblogs.com/campus/fzu/2024C/homework/13282学号 222200424姓名 赵伟豪编程练习3.13.23.33.43.53.63.73.8示例程序3.13.23.33.43.53.63.73.83.93.10总结与收获…

浏览器的渲染原理

浏览器渲染原理 五个渲染流程Parse 阶段:解析 HTMLStyle 阶段:样式计算三个阶段:收集,划分和索引所有样式表中存在的样式规则 访问每个元素并找到适用于该元素的所有规则,CSS 引擎遍历 DOM 节点,进行选择器匹配,并且匹配的节点执行样式设置 结合层叠规则和其他信息为节点…