首页 > 其他分享 >Prometheus 监控系统

Prometheus 监控系统

时间:2024-09-20 23:24:29浏览次数:1  
标签:node name kubernetes 系统 prometheus metrics Prometheus 监控

目录

1.Prometheus 概述

  Prometheus是一个开源的服务监控系统和时序数据库,其提供了通用的数据模型和快捷数据采集、存储和查询接口。它的核心组件 Prometheus server 会定期从静态配置的监控目标或者基于服务发现自动配置的目标中进行拉取数据,新拉取到的数据会持久化到存储设备当中。
  每个被监控的主机都可以通过专用的 exporter 程序提供输出监控指标数据的接口,它会在目标处收集监控数据,并暴露出一个 HTTP 接口供 Prometheus server 查询, Prometheus 通过基于 HTTP 的 pull 的方式来周期性的采集数据,默认时间是 15s 抓取一次。
  抓取到的指标数据会被以时间序列的形式保存在内存中,并且定时刷到磁盘上,默认是两个小时回刷一次。并且为了防止 Prometheus 发生崩溃或重启时能够恢复数据, Prometheus 也提供了类似 MySQL 中 binlog 一样的 wal 预写日志,当 Prometheus 崩溃重启时,会读这个预写日志来恢复数据。
  对于短时间执行的脚本任务或者不好直接 pull 指标数据的服务,Prometheus 提供了 Pushgateway 给这些任务将服务指标数据主动 push 到 Pushgateway 并临时存储,然后等待 Prometheus server 完成数据的采集。
  任何被监控的目标都需要事先纳入到监控系统中才能进行时序数据采集、存储、告警和展示,监控目标可以通过配置信息以静态形式指定,也可以让 Prometheus 通过服务发现的机制进行动态管理。
  Prometheus 能够直接把K8S的 API Server 作为服务发现系统使用,进而动态发现和监控K8S集群中的所有可被监控的对象。

Prometheus 官网地址:https://prometheus.io
Prometheus github 地址:https://github.com/prometheus

(1)TSDB 作为 Prometheus 的存储引擎完美契合了监控数据的应用场景

●存储的数据量级十分庞大
●大部分时间都是写入操作
●写入操作几乎是顺序添加,大多数时候数据都以时间排序
●很少更新数据,大多数情况在数据被采集到数秒或者数分钟后就会被写入数据库
●删除操作一般为区块删除,选定开始的历史时间并指定后续的区块。很少单独删除某个时间或者分开的随机时间的数据
●基本数据大,一般超过内存大小。一般选取的只是其一小部分且没有规律,缓存几乎不起任何作用
●读操作是十分典型的升序或者降序的顺序读
●高并发的读操作十分常见

(2)Prometheus 的特点

●多维数据模型:由度量名称和键值对标识的时间序列数据
时间序列数据:按照时间顺序记录系统、设备状态变化的数据,每个数据称为一个样本;服务器指标数据、应用程序性能监控数据、网络数据等都是时序数据
内置时间序列(Time Series)数据库:Prometheus ;外置的远端存储通常会用:InfluxDB、OpenTSDB 等
●promQL 一种灵活的查询语言,可以利用多维数据完成复杂查询
●基于 HTTP 的 pull(拉取)方式采集时间序列数据
●同时支持 PushGateway 组件收集数据
●通过静态配置或服务发现发现目标
●支持作为数据源接入 Grafana

(3)Prometheus的主要组件

(1)prometheus server

是Prometheus服务的核心组件。通过http pull拉取的方式从监控目标采集监控指标数据(时序数据);作为时序数据库持久化存储监控指标数据;
配置告警规则,当触告警时会生成告警通知发送给alertmanager;配置service discovery服务发现,可通过文件、cousul、K8S等方式自动发现监控目标target

(2)exporter

指标暴露器,用于从原生不支持prometheus直接采集监控指标数据的系统或应用等对象收集和汇总监控指标数据,并暴露http接口供prometheus server采集数据
node-exporter、kube-state-matrics、nginx/mysqld/redis-exporter、cADvisor、blackbox-exporter

(3)alertmanager

接收prometheus server发来的告警通知,负责对告警通知分组、去重,再通过邮件、钉钉、企业微信等方式发送给接收人

(4)pushgateway

作为临时中转站,接收一些短期任务或只能推送数据的任务发送的监控指标数据,临时存储这些监控指标数据并统一供prometheus server采集数据

(5)grafana

外置的监控数据展示平台,接入prometheus的数据源,通过promQL查询数据,以图形化形式展示监控数据

(4)Prometheus 的局限性

●Prometheus 是一款指标监控系统,不适合存储事件及日志等;它更多地展示的是趋势性的监控,而非精准数据;
●Prometheus 认为只有最近的监控数据才有查询的需要,其本地存储的设计初衷只是保存短期(例如一个月)数据,因而不支持针对大量的历史数据进行存储;
若需要存储长期的历史数据,建议基于远端存储机制将数据保存于 InfluxDB 或 OpenTSDB 等系统中;
●Prometheus 的集群机制成熟度不高,可基于 Thanos 或 Cortex 实现 Prometheus 集群的高可用及联邦集群。

2.Zabbix和Prometheus的区别?如何选择?

(1)Zabbix

更适合于传统业务架构的物理机、虚拟机环境的监控,对服务器系统和传统应用组件监控比较成熟,但是对容器的支持比较差。
数据存储主要采用的是关系型数据库,会随着被监控节点数量的增加,关系型数据库的负载压力也会变大,监控数据的读写也会变慢。
对大规模集群监控的性能比prometheus要弱一些,可适用于单集群规模不超过1000台节点的场景。

(2)Prometheus

除了传统业务架构,还能支持云环境、K8S容器集群的监控,是目前容器监控最好的解决方案。
数据存储采用的是时序数据库,大大的节省存储空间,还能提升查询效率。
单集群能支持的节点规模更大,通常超过2000台节点、服务数量大于1000个的时候建议直接上Prometheus。

3.Prometheus的工作流程

1)prometheus server通过静态配置或服务发现的方式获取监控目标target(通过exporter或pushgateway暴露的http接口)
2)prometheus server通过http pull拉取的方式从监控目标target采集监控指标数据
3)prometheus server将采集到的监控指标数据通过时序数据库持久化存储到本地磁盘或外置存储中
4)prometheus server通过将采集到的监控指标数据与本地配置的监控告警规则进行计算比对,如果触发告警则生成告警通知发送给alertmanager
5)alertmanager接收到prometheus server发来的告警通知后,对告警通知分组、去重,再通过邮件、钉钉、企业微信等方式发送给接收人
6)prometheus支持原生的web UI或grafana接入prometheus数据源,通过promQL查询数据,以图形化形式展示监控数据

4.helm快速部署 Prometheus 和 Grafana

master

node

pv1、2



master





一键部署Prometheus


等待pod开启

一键部署Grafana

镜像加速















5.部署 Prometheus

Prometheust Server 端安装和相关配置
(1)上传 prometheus-2.35.0.linux-amd64.tar.gz 到 /opt 目录中,并解压

systemctl stop firewalld
setenforce 0

cd /opt/
tar xf prometheus-2.35.0.linux-amd64.tar.gz
mv prometheus-2.35.0.linux-amd64 /usr/local/prometheus

cat /usr/local/prometheus/prometheus.yml | grep -v "^#"
global:					#用于prometheus的全局配置,比如采集间隔,抓取超时时间等
  scrape_interval: 15s			#采集目标主机监控数据的时间间隔,默认为1m
  evaluation_interval: 15s 		#触发告警生成alert的时间间隔,默认是1m
  # scrape_timeout is set to the global default (10s).
  scrape_timeout: 10s			#数据采集超时时间,默认10s

alerting:				#用于alertmanager实例的配置,支持静态配置和动态服务发现的机制
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

rule_files:				#用于加载告警规则相关的文件路径的配置,可以使用文件名通配机制
  # - "first_rules.yml"
  # - "second_rules.yml"

scrape_configs:			#用于采集时序数据源的配置
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"		#每个被监控实例的集合用job_name命名,支持静态配置(static_configs)和动态服务发现的机制(*_sd_configs)

    # metrics_path defaults to '/metrics'
    metrics_path: '/metrics'    #指标数据采集路径,默认为 /metrics
    # scheme defaults to 'http'.

    static_configs:				#静态目标配置,固定从某个target拉取数据
      - targets: ["localhost:9090"]

(2)配置系统启动文件,启动 Prometheust

cat > /usr/lib/systemd/system/prometheus.service <<'EOF'
[Unit]
Description=Prometheus Server
Documentation=https://prometheus.io
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/prometheus/prometheus \
--config.file=/usr/local/prometheus/prometheus.yml \
--storage.tsdb.path=/usr/local/prometheus/data/ \
--storage.tsdb.retention.time=15d \
--web.enable-lifecycle
  
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

(3)启动

systemctl start prometheus
systemctl enable prometheus

netstat -natp | grep :9090

浏览器访问:http://192.168.80.30:9090 ,访问到 Prometheus 的 Web UI 界面
点击页面的 Status -> Targets,如看到 Target 状态都为 UP,说明 Prometheus 能正常采集到数据
http://192.168.80.30:9090/metrics ,可以看到 Prometheus 采集到自己的指标数据,其中 Help 字段用于解释当前指标的含义,Type 字段用于说明数据的类型
以 go_ 为前缀的指标是关于 Go 运行时相关的指标,比如垃圾回收时间、goroutine 数量等,这些都是 Go 客户端库特有的

6.部署 Exporters

(1)部署 Node Exporter 监控系统级指标

(1)上传 node_exporter-1.3.1.linux-amd64.tar.gz 到 /opt 目录中,并解压

cd /opt/
tar xf node_exporter-1.3.1.linux-amd64.tar.gz
mv node_exporter-1.3.1.linux-amd64/node_exporter /usr/local/bin

(2)配置启动文件

cat > /usr/lib/systemd/system/node_exporter.service <<'EOF'
[Unit]
Description=node_exporter
Documentation=https://prometheus.io/
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/node_exporter \
--collector.ntp \
--collector.mountstats \
--collector.systemd \
--collector.tcpstat

ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

(3)启动

systemctl start node_exporter
systemctl enable node_exporter
netstat -natp | grep :9100

浏览器访问:http://192.168.80.30:9100/metrics ,可以看到 Node Exporter 采集到的指标数据

常用的各指标:

●node_cpu_seconds_total
●node_memory_MemTotal_bytes
●node_filesystem_size_bytes{mount_point=PATH}
●node_system_unit_state{name=}
●node_vmstat_pswpin:系统每秒从磁盘读到内存的字节数
●node_vmstat_pswpout:系统每秒钟从内存写到磁盘的字节数

更多指标介绍:https://github.com/prometheus/node_exporter

(4)修改 prometheus 配置文件,加入到 prometheus 监控中

vim /usr/local/prometheus/prometheus.yml
#在尾部增加如下内容
  - job_name: nodes
    metrics_path: "/metrics"
    static_configs:
    - targets:
	  - 192.168.80.30:9100
	  - 192.168.80.11:9100
	  - 192.168.80.12:9100
      labels:
        service: kubernetes

(5)重新载入配置

curl -X POST http://192.168.80.30:9090/-/reload    或    systemctl reload prometheus
浏览器查看 Prometheus 页面的 Status -> Targets

(2)监控 MySQL 配置示例

在 MySQL 服务器上操作
(1)上传 mysqld_exporter-0.14.0.linux-amd64.tar.gz 到 /opt 目录中,并解压

cd /opt/
tar xf mysqld_exporter-0.14.0.linux-amd64.tar.gz
mv mysqld_exporter-0.14.0.linux-amd64/mysqld_exporter /usr/local/bin/

(2)配置启动文件

cat > /usr/lib/systemd/system/mysqld_exporter.service <<'EOF'
[Unit]
Description=mysqld_exporter
Documentation=https://prometheus.io/
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/mysqld_exporter --config.my-cnf=/etc/my.cnf

ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

(3)修改 MySQL 配置文件

vim /etc/my.cnf
[client]
......
host=localhost
user=exporter
password=abc123

(4)授权 exporter 用户

mysql -uroot -pabc123
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'localhost' IDENTIFIED BY 'abc123';

(5)重启服务

systemctl restart mysqld
systemctl start mysqld_exporter
systemctl enable mysqld_exporter

netstat -natp | grep :9104

在 Prometheus 服务器上操作
(1)修改 prometheus 配置文件,加入到 prometheus 监控中

vim /usr/local/prometheus/prometheus.yml
#在尾部增加如下内容
  - job_name: mysqld
    metrics_path: "/metrics"
    static_configs:
    - targets:
          - 192.168.80.15:9104
      labels:
        service: mysqld

(2)重新载入配置

curl -X POST http://192.168.80.30:9090/-/reload    或    systemctl reload prometheus
浏览器查看 Prometheus 页面的 Status -> Targets

(3)监控 Nginx 配置示例

在 Nginx 服务器上操作
下载 nginx-exporter 地址:https://github.com/hnlq715/nginx-vts-exporter/releases/download/v0.10.3/nginx-vts-exporter-0.10.3.linux-amd64.tar.gz
下载 nginx 地址:http://nginx.org/download/
下载 nginx 插件地址:https://github.com/vozlt/nginx-module-vts/tags

(1)解压 nginx 插件

cd /opt
tar xf nginx-module-vts-0.1.18.tar.gz
mv nginx-module-vts-0.1.18 /usr/local/nginx-module-vts

(2)安装 Nginx

yum -y install pcre-devel zlib-devel openssl-devel gcc gcc-c++ make
useradd -M -s /sbin/nologin nginx

cd /opt
tar xf nginx-1.18.0.tar.gz

cd nginx-1.18.0/
./configure --prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module \
--with-http_ssl_module \
--add-module=/usr/local/nginx-module-vts

make & make install

(3)修改 nginx 配置文件,启动 nginx

vim /usr/local/nginx/conf/nginx.conf
http {
    vhost_traffic_status_zone;					#添加
    vhost_traffic_status_filter_by_host on;		#添加,开启此功能,在 Nginx 配置有多个 server_name 的情况下,会根据不同的 server_name 进行流量的统计,否则默认会把流量全部计算到第一个 server_name 上
	......
	server {
	......
	}
	
    server {
        vhost_traffic_status off;		#在不想统计流量的 server 区域,可禁用 vhost_traffic_status
        listen 8080;
        allow 127.0.0.1;
        allow 192.168.80.30;			#设置为 prometheus 的 ip 地址

        location /nginx-status {
            stub_status on;
            access_log off;
        }

        location /status {
            vhost_traffic_status_display;
            vhost_traffic_status_display_format html;
        }
    }
}

#假如 nginx 没有规范配置 server_name 或者无需进行监控的 server 上,那么建议在此 vhost 上禁用统计监控功能。否则会出现 127.0.0.1、hostname 等的域名监控信息。

ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
nginx -t

cat > /lib/systemd/system/nginx.service <<'EOF'
[Unit]
Description=nginx
After=network.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

systemctl start nginx
systemctl enable nginx

浏览器访问:http://192.168.80.15:8080/status ,可以看到 Nginx Vhost Traffic Status 的页面信息

(4)解压 nginx-exporter,启动 nginx-exporter

cd /opt/
tar -zxvf nginx-vts-exporter-0.10.3.linux-amd64.tar.gz
mv nginx-vts-exporter-0.10.3.linux-amd64/nginx-vts-exporter /usr/local/bin/

cat > /usr/lib/systemd/system/nginx-exporter.service <<'EOF'
[Unit]
Description=nginx-exporter
Documentation=https://prometheus.io/
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/nginx-vts-exporter -nginx.scrape_uri=http://localhost:8080/status/format/json

ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

systemctl start nginx-exporter
systemctl enable nginx-exporter
netstat -natp | grep :9913

在 Prometheus 服务器上操作
(1)修改 prometheus 配置文件,加入到 prometheus 监控中

vim /usr/local/prometheus/prometheus.yml
#在尾部增加如下内容
  - job_name: nginx
    metrics_path: "/metrics"
    static_configs:
    - targets:
          - 192.168.80.15:9913
      labels:
        service: nginx

(2)重新载入配置

curl -X POST http://192.168.80.30:9090/-/reload    或    systemctl reload prometheus
浏览器查看 Prometheus 页面的 Status -> Targets

7.部署 Grafana 进行展示

(1)下载和安装
下载地址:https://grafana.com/grafana/download
https://mirrors.bfsu.edu.cn/grafana/yum/rpm/

yum install -y grafana-7.4.0-1.x86_64.rpm
systemctl start grafana-server
systemctl enable grafana-server
netstat -natp | grep :3000

浏览器访问:http://192.168.80.30:3000 ,默认账号和密码为 admin/admin

(2)配置数据源

Configuration -> Data Sources -> Add data source -> 选择 Prometheus
HTTP -> URL 输入 http://192.168.80.30:9090
点击 Save & Test
点击 上方菜单 Dashboards,Import 所有默认模板
Dashboards -> Manage ,选择 Prometheus 2.0 Stats 或 Prometheus Stats 即可看到 Prometheus job 实例的监控图像

(3)导入 grafana 监控面板
浏览器访问:https://grafana.com/grafana/dashboards ,在页面中搜索 node exporter ,选择适合的面板,点击 Copy ID 或者 Download JSON

在 grafana 页面中,+ Create -> Import ,输入面板 ID 号或者上传 JSON 文件,点击 Load,即可导入监控面板

8.部署 Prometheus 服务发现

(1)基于文件的服务发现

基于文件的服务发现是仅仅略优于静态配置的服务发现方式,它不依赖于任何平台或第三方服务,因而也是最为简单和通用的实现方式。
Prometheus Server 会定期从文件中加载 Target 信息,文件可使用 YAML 和 JSON 格式,它含有定义的 Target 列表,以及可选的标签信息。

(1)创建用于服务发现的文件,在文件中配置所需的 target

cd /usr/local/prometheus
mkdir targets

vim targets/node-exporter.yaml
- targets:
  - 192.168.80.30:9100
  - 192.168.80.15:9100
  labels:
    app: node-exporter
    job: node


vim targets/mysqld-exporter.yaml
- targets:
  - 192.168.80.30:9104
  - 192.168.80.15:9104
  labels:
    app: mysqld-exporter
    job: mysqld

#修改 prometheus 配置文件,发现 target 的配置,定义在配置文件的 job 之中
vim /usr/local/prometheus/prometheus.yml
......
scrape_configs:
  - job_name: nodes
    file_sd_configs:                  #指定使用文件服务发现
    - files:                          #指定要加载的文件列表
      - targets/node*.yaml            #文件加载支持通配符
      refresh_interval: 2m            #每隔 2 分钟重新加载一次文件中定义的 Targets,默认为 5m
  
  - job_name: mysqld
    file_sd_configs:
    - files:
      - targets/mysqld*.yaml
      refresh_interval: 2m


systemctl reload prometheus
浏览器查看 Prometheus 页面的 Status -> Targets

(2)基于 Consul 的服务发现

Consul 是一款基于 golang 开发的开源工具,主要面向分布式,服务化的系统提供服务注册、服务发现和配置管理的功能。
提供服务注册/发现、健康检查、Key/Value存储、多数据中心和分布式一致性保证等功能。

下载地址:https://www.consul.io/downloads/

(1)部署 Consul 服务

cd /opt/
unzip consul_1.9.2_linux_amd64.zip
mv consul /usr/local/bin/

#创建 Consul 服务的数据目录和配置目录
mkdir -p /usr/local/consul/{data,conf,logs}

#使用 server 模式启动 Consul 服务
consul agent \
-server \
-bootstrap \
-ui \
-data-dir=/usr/local/consul/data \
-config-dir=/usr/local/consul/conf \
-bind=192.168.80.14 \
-client=0.0.0.0 \
-node=consul-server01 &> /usr/local/consul/logs/consul.log &

#查看 consul 集群成员
consul members

(2)在 Consul 上注册 Services
在配置目录中添加文件

vim /usr/local/consul/conf/nodes.json
{
  "services": [
    {
      "id": "node_exporter-node01",
      "name": "node01",
      "address": "192.168.80.30",
      "port": 9100,
      "tags": ["nodes"],
      "checks": [{
        "http": "http://192.168.80.30:9100/metrics",
        "interval": "5s"
      }]
    },
    {
      "id": "node_exporter-node02",
      "name": "node02",
      "address": "192.168.80.15",
      "port": 9100,
      "tags": ["nodes"],
      "checks": [{
        "http": "http://192.168.80.15:9100/metrics",
        "interval": "5s"
      }]
    }
  ]
}

#让 consul 重新加载配置信息
consul reload		

浏览器访问:http://192.168.80.30:8500

(3)修改 prometheus 配置文件

vim /usr/local/prometheus/prometheus.yml
......
  - job_name: nodes
    consul_sd_configs:                  #指定使用 consul 服务发现
    - server: 192.168.80.30:8500        #指定 consul 服务的端点列表
      tags:                             #指定 consul 服务发现的 services 中哪些 service 能够加入到 prometheus 监控的标签
      - nodes
      refresh_interval: 2m


systemctl reload prometheus
浏览器查看 Prometheus 页面的 Status -> Targets

#让 consul 注销 Service
consul services deregister -id="node_exporter-node02"

#重新注册
consul services register /etc/consul/nodes.json

(3)基于 Kubernetes API 的服务发现

基于 Kubernetes API 的服务发现机制,支持将 API Server 中 Node、Service、Endpoint、Pod 和 Ingress 等资源类型下相应的各资源对象视作 target, 并持续监视相关资源的变动
●Node、Service、Endpoint、Pod 和 Ingress 资源分别由各自的发现机制进行定义
●负责发现每种类型资源对象的组件,在 Prometheus 中称为一个 role
●支持在集群上基于 DaemonSet 控制器部署 node-exporter 后发现各 Node 节点,也可以通过 kubelet 来作为 Prometheus 发现各 Node 节点的入口

基于 Kubernetes 发现机制的部分配置参数

# The API server addresses. If left empty, Prometheus is assumed to run inside of the cluster and will discover API servers automatically
and use the pod's
# CA certificate and bearer token file at /var/run/secrets/kubernetes.io/serviceaccount/.
[ api_server: <host> ]

# The Kubernetes role of entities that should be discovered. One of endpoints, service, pod, node, or ingress.
role: <string>

# Optional authentication information used to authenticate to the API server.
# Note that 'basic_auth', 'bearer_token'和'bearer_token_file' 等认证方式互斥;
[ bearer_token: <secret> ]
[ bearer_token_file: <filename> ]

# TLS configuration.
tls_config:
# CA certificate to validate API server certificate with.
[ ca_file: <filename> ]

# Certificate and key files for client cert authentication to the server.
[ cert_file: <filename> ]
[ key_file: <filename> ]

# ServerName extension to indicate the name of the server.
[ server_name: <string> ]

# Optional namespace discovery. If omitted, all namespaces are used.
namespaces:
names:
[ - <string> ]

9.Kubernetes 集群部署 Prometheus 和 Grafana

(1)实验环境

控制节点/master01		192.168.80.10
工作节点/node01			192.168.80.11
工作节点/node02			192.168.80.12

(2)node-exporter 安装

#创建监控 namespace
kubectl create ns monitor-sa

#部署 node-exporter
mkdir /opt/prometheus
cd /opt/prometheus/

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
      containers:
      - name: node-exporter
        image: prom/node-exporter:v0.16.0
        ports:
        - containerPort: 9100
        resources:
          requests:
            cpu: 0.15		#这个容器运行至少需要0.15核cpu
        securityContext:
          privileged: true	#开启特权模式
        args:
        - --path.procfs
        - /host/proc
        - --path.sysfs
        - /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
      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: /

#hostNetwork、hostIPC、hostPID都为True时,表示这个Pod里的所有容器,会直接使用宿主机的网络,直接与宿主机进行IPC(进程间通信)通信,可以看到宿主机里正在运行的所有进程。加入了hostNetwork:true会直接将我们的宿主机的9100端口映射出来,从而不需要创建service在我们的宿主机上就会有一个9100的端口。

kubectl apply -f node-export.yaml

kubectl get pods -n monitor-sa -o wide

#通过 node-exporter 采集数据
node-exporter 默认的监听端口是 9100,可以执行 curl http://主机ip:9100/metrics 获取到主机的所有监控数据

curl -Ls http://192.168.80.10:9100/metrics | grep node_cpu_seconds
# HELP node_cpu_seconds_total Seconds the cpus spent in each mode.		#Help 用于解释当前指标的含义
# TYPE node_cpu_seconds_total counter				#Type 用于说明数据的类型,这是一个 counter(计数器)类型的数据
node_cpu_seconds_total{cpu="0",mode="idle"} 1076.15		#接下来就是具体的指标的值
node_cpu_seconds_total{cpu="0",mode="iowait"} 0.99
node_cpu_seconds_total{cpu="0",mode="irq"} 0
node_cpu_seconds_total{cpu="0",mode="nice"} 0
node_cpu_seconds_total{cpu="0",mode="softirq"} 3.15
node_cpu_seconds_total{cpu="0",mode="steal"} 0
node_cpu_seconds_total{cpu="0",mode="system"} 23.17
node_cpu_seconds_total{cpu="0",mode="user"} 24.49
node_cpu_seconds_total{cpu="1",mode="idle"} 1079.71
node_cpu_seconds_total{cpu="1",mode="iowait"} 0.75
node_cpu_seconds_total{cpu="1",mode="irq"} 0
node_cpu_seconds_total{cpu="1",mode="nice"} 0
node_cpu_seconds_total{cpu="1",mode="softirq"} 3.6
node_cpu_seconds_total{cpu="1",mode="steal"} 0
node_cpu_seconds_total{cpu="1",mode="system"} 22.04
node_cpu_seconds_total{cpu="1",mode="user"} 25.6

curl -Ls http://192.168.80.10:9100/metrics | grep node_load
# HELP node_load1 1m load average.
# TYPE node_load1 gauge
node_load1 0.24
# HELP node_load15 15m load average.
# TYPE node_load15 gauge
node_load15 0.16
# HELP node_load5 5m load average.
# TYPE node_load5 gauge
node_load5 0.18

(3)Prometheus 安装和配置

(1)创建 sa 账号,对 sa 做 rbac 授权
创建一个 sa 账号 monitor

kubectl create serviceaccount monitor -n monitor-sa

#把 sa 账号 monitor 通过 clusterrolebing 绑定到 clusterrole 上
kubectl create clusterrolebinding monitor-clusterrolebinding -n monitor-sa --clusterrole=cluster-admin  --serviceaccount=monitor-sa:monitor

(2)创建一个 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.80.20: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/<node_name>/proxy/metrics/cadvisor
        #${1}是__meta_kubernetes_node_name获取到的值
        #最后通过https://<apiserver_address>/api/v1/nodes/<node_name>/proxy/metrics/cadvisor来获取对应节点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

kubectl apply -f prometheus-cfg.yaml

(3)通过 deployment 部署 prometheus
将 prometheus 调度到 node1 节点,在 node1 节点创建 prometheus 数据存储目录

mkdir /data && chmod 777 /data

#通过 deployment 部署 prometheus
vim 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

kubectl apply -f prometheus-deploy.yaml
kubectl get pods -o wide -n monitor-sa 

(4)给 prometheus pod 创建一个 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

kubectl apply -f prometheus-svc.yaml
kubectl get svc -n monitor-sa
NAME         TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
prometheus   NodePort   10.107.188.51   <none>        9090:31000/TCP   86s

#通过上面可以看到 service 在 node 节点上映射的端口是 31000,这样我们访问 k8s 集群的 node 节点的 ip:31000,就可以访问到 prometheus 的 web ui 界面了。
浏览器访问 http://192.168.80.11:31000

#点击页面的Status->Targets,如看到所有 Target 状态都为 UP,说明我们配置的服务发现可以正常采集数据

#查询 K8S 集群中一分钟之内每个 Pod 的 CPU 使用率
sum by (name)( rate(container_cpu_usage_seconds_total{image!="", name!=""}[1m] ) )

(4)Prometheus 配置热加载

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

kubectl get pods -n monitor-sa -o wide -l app=prometheus
NAME                                 READY   STATUS    RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
prometheus-server-75fb7f8fc6-8vxwj   1/1     Running   0          18h   10.244.1.3   node01   <none>           <none>

#想要使配置生效可用如下命令热加载
curl -X POST -Ls http://10.244.1.3:9090/-/reload 

#查看 log
kubectl logs -n monitor-sa prometheus-server-75fb7f8fc6-8vxwj | grep "Loading configuration file" 

###一般热加载速度比较慢,可以暴力重启prometheus,如修改上面的 prometheus-cfg.yaml 文件之后,可用如下命令:
#可执行先强制删除,然后再通过 apply 更新
kubectl delete -f prometheus-cfg.yaml
kubectl delete -f prometheus-deploy.yaml
kubectl apply -f prometheus-cfg.yaml
kubectl apply -f prometheus-deploy.yaml

注意:线上环境最好使用热加载,暴力删除可能造成监控数据的丢失

(5)Grafana 安装

vim 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: grafana/grafana:5.0.4
        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

kubectl apply -f grafana.yaml
kubectl get pods -n kube-system -l task=monitoring -o wide

kubectl get svc -n kube-system | grep grafana  
monitoring-grafana   NodePort    10.96.53.95   <none>        80:32087/TCP             26s 

(6)Grafana 配置

(1)浏览器访问http://192.168.80.11:32087 ,登陆 grafana
(2)开始配置 grafana 的 web 界面:选择 Add data source
【Name】设置成 Prometheus
【Type】选择 Prometheus
【URL】设置成 http://prometheus.monitor-sa.svc:9090 #使用service的集群内部端口配置服务端地址
点击 【Save & Test】

(3)导入监控模板
官方链接搜索:https://grafana.com/dashboards?dataSource=prometheus&search=kubernetes

(4)监控 node 状态
点击左侧+号选择【Import】
点击【Upload .json File】导入 node_exporter.json 模板
【Prometheus】选择 Prometheus
点击【Import】

(5)监控 容器 状态
点击左侧+号选择【Import】
点击【Upload .json File】导入 docker_rev1.json 模板
【Prometheus】选择 Prometheus
点击【Import】

(7)k8s 部署 kube-state-metrics 组件

(1)安装 kube-state-metrics 组件
创建 sa,并对 sa 授权

vim 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

kubectl apply -f kube-state-metrics-rbac.yaml

#安装 kube-state-metrics 组件和 service
vim 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
        ports:
        - containerPort: 8080
---
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

kubectl apply -f kube-state-metrics-deploy_svc.yaml
kubectl get pods,svc -n kube-system -l app=kube-state-metrics

(2)Grafana 配置
监控 k8s 群集状态
点击左侧+号选择【Import】
点击【Upload .json File】导入 kubernetes-cluster-prometheus_rev4.json 模板
【Prometheus】选择 Prometheus
点击【Import】

监控 k8s 群集性能状态
点击左侧+号选择【Import】
点击【Upload .json File】导入 kubernetes-cluster-monitoring-via-prometheus_rev3.json 模板
【Prometheus】选择 Prometheus
点击【Import】

(8)kubernetes 配置 alertmanager 发送报警到邮箱

(1)Prometheus报警处理流程

1)Prometheus Server 监控目标主机上暴露的 http接口(假设接口A),通过Promethes配置的'scrape_interval' 定义的时间间隔, 定期采集目标主机上监控数据。
2)当接口A不可用的时候,Server 端会持续的尝试从接口中取数据,直到 "scrape_timeout" 时间后停止尝试。 这时候把接口的状态变为 "DOWN"。
3)Prometheus 同时根据配置的 evaluation_interval 的时间间隔,定期(默认1min)的对 Alert Rule 进行评估; 当到达评估周期的时候,发现接口A为 DOWN,即 UP=0 为真,激活 Alert,进入 PENDING 状态,并记录当前 active 的时间;
4)当下一个 alert rule 的评估周期到来的时候,发现 UP=0 继续为真,然后判断警报 Active 的时间是否已经超出 rule 里的 for 持续时间,如果未超出,则进入下一个评估周期;如果时间超出,则 alert 的状态变为 FIRING;同时调用 Alertmanager 接口, 发送相关报警数据。
5)AlertManager 收到报警数据后,会将警报信息进行分组,然后根据 alertmanager 配置的 group_wait 时间先进行等待。等 wait 时间过后再发送报警信息。
6)属于同一个 Alert Group的警报,在等待的过程中可能进入新的 alert,如果之前的报警已经成功发出,那么间隔 group_interval 的时间间隔后再重新发送报警信息。比如配置的是邮件报警,那么同属一个 group 的报警信息会汇总在一个邮件里进行发送。
7)如果 Alert Group里的警报一直没发生变化并且已经成功发送,等待 repeat_interval 时间间隔之后再重复发送相同的报警邮件; 如果之前的警报没有成功发送,则相当于触发第6条条件,则需要等待 group_interval 时间间隔后重复发送。
8)同时最后至于警报信息具体发给谁,满足什么样的条件下指定警报接收人,设置不同报警发送频率,这里使用 alertmanager 的 route 路由规则进行配置。

(2)Prometheus 及 Alertmanager 配置

(1)创建 alertmanager 配置文件

vim alertmanager-cm.yaml
---
kind: ConfigMap
apiVersion: v1
metadata:
  name: alertmanager
  namespace: monitor-sa
data:
  alertmanager.yml: |-
    global:                    #设置发件人邮箱信息
      resolve_timeout: 1m
      smtp_smarthost: 'smtp.qq.com:25'
      smtp_from: '[email protected]'
      smtp_auth_username: '[email protected]'
      smtp_auth_password: 'zzkqqtejcbenbidh'    #此处为授权码,登录QQ邮箱【设置】->【账户】中的【生成授权码】获取
      smtp_require_tls: false
    route:                        #用于设置告警的分发策略
      group_by: [alertname]         #采用哪个标签来作为分组依据
      group_wait: 10s               #组告警等待时间。也就是告警产生后等待10s,如果有同组告警一起发出
      group_interval: 10s           #上下两组发送告警的间隔时间
      repeat_interval: 10m          #重复发送告警的时间,减少相同邮件的发送频率,默认是1h
      receiver: default-receiver    #定义谁来收告警
    receivers:                    #设置收件人邮箱信息
    - name: 'default-receiver'
      email_configs:
      - to: '[email protected]'    #设置收件人邮箱地址
        send_resolved: true

kubectl apply -f alertmanager-cm.yaml

(2)创建 prometheus 和告警规则配置文件
上传 prometheus-alertmanager-cfg.yaml 文件

#删除之前的配置,更新配置
kubectl delete -f prometheus-cfg.yaml
kubectl apply -f prometheus-alertmanager-cfg.yaml

kubectl get cm -n monitor-sa 
alertmanager        1      2m29s
kube-root-ca.crt    1      14h
prometheus-config   2      29s

(3)安装 prometheus 和 alertmanager
生成一个 secret 资源 etcd-certs,这个在部署 prometheus 需要,用于监控 etcd 相关资源

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

#更新资源清单 yaml 文件,安装 prometheus 和 alertmanager
vim prometheus-alertmanager-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
      serviceAccountName: monitor
      containers:
      - name: prometheus
        image: prom/prometheus:v2.2.1
        imagePullPolicy: IfNotPresent
        command:
        - "/bin/prometheus"
        args:
        - "--config.file=/etc/prometheus/prometheus.yml"
        - "--storage.tsdb.path=/prometheus"
        - "--storage.tsdb.retention=24h"
        - "--web.enable-lifecycle"
        ports:
        - containerPort: 9090
          protocol: TCP
        volumeMounts:
        - mountPath: /etc/prometheus
          name: prometheus-config
        - mountPath: /prometheus/
          name: prometheus-storage-volume
        - name: k8s-certs
          mountPath: /var/run/secrets/kubernetes.io/k8s-certs/etcd/
        - name: localtime
          mountPath: /etc/localtime
      - name: alertmanager
        image: prom/alertmanager:v0.14.0
        imagePullPolicy: IfNotPresent
        args:
        - "--config.file=/etc/alertmanager/alertmanager.yml"
        - "--log.level=debug"
        ports:
        - containerPort: 9093
          protocol: TCP
          name: alertmanager
        volumeMounts:
        - name: alertmanager-config
          mountPath: /etc/alertmanager
        - name: alertmanager-storage
          mountPath: /alertmanager
        - name: localtime
          mountPath: /etc/localtime
      volumes:
        - name: prometheus-config
          configMap:
            name: prometheus-config
        - name: prometheus-storage-volume
          hostPath:
           path: /data
           type: Directory
        - name: k8s-certs
          secret:
           secretName: etcd-certs
        - name: alertmanager-config
          configMap:
            name: alertmanager
        - name: alertmanager-storage
          hostPath:
           path: /data/alertmanager
           type: DirectoryOrCreate
        - name: localtime
          hostPath:
           path: /usr/share/zoneinfo/Asia/Shanghai

kubectl delete -f prometheus-deploy.yaml
kubectl apply -f prometheus-alertmanager-deploy.yaml
kubectl get pods -n monitor-sa | grep prometheus

(4)部署 alertmanager 的 service,方便在浏览器访问

vim alertmanager-svc.yaml
---
apiVersion: v1
kind: Service
metadata:
  labels:
    name: prometheus
    kubernetes.io/cluster-service: 'true'
  name: alertmanager
  namespace: monitor-sa
spec:
  ports:
  - name: alertmanager
    nodePort: 30066
    port: 9093
    protocol: TCP
    targetPort: 9093
  selector:
    app: prometheus
  sessionAffinity: None
  type: NodePort

kubectl apply -f alertmanager-svc.yaml

#查看 service 在物理机映射的端口
kubectl get svc -n monitor-sa
NAME           TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
alertmanager   NodePort   10.105.125.219   <none>        9093:30066/TCP   38s
prometheus     NodePort   10.107.188.51    <none>        9090:31000/TCP   23h
#此时可以看到 prometheus 的 service 在物理机映射的端口是 31000,alertmanager 的 service 在物理机映射的端口是 30066

浏览器访问 http://192.168.80.11:30066/#/alerts ,登陆 alertmanager

查看接收到的邮件报警,可以发现与 alertmanager 显示的告警一致

浏览器访问 http://192.168.80.11:31000 ,点击页面的 Status->Targets,查看 prometheus 的 targets

(3)处理 kube-proxy 监控告警

kubectl edit configmap kube-proxy -n kube-system
......
metricsBindAddress: "0.0.0.0:10249"
#因为 kube-proxy 默认端口10249是监听在 127.0.0.1 上的,需要改成监听到物理节点上

#重新启动 kube-proxy
kubectl get pods -n kube-system | grep kube-proxy |awk '{print $1}' | xargs kubectl delete pods -n kube-system

ss  -antulp |grep :10249
tcp    LISTEN     0      128      :::10249                :::*                   users:(("kube-proxy",pid=55675,fd=15))

#alert 查看
点击 prometheus 页面的 Alerts,点开一个告警项,FIRING 表示 prometheus 已经将告警发给 alertmanager,在 Alertmanager 中可以看到有一个 alert。登录到 浏览器访问 http://192.168.80.11:30066/#/alerts ,登陆 alertmanager 即可看到。

标签:node,name,kubernetes,系统,prometheus,metrics,Prometheus,监控
From: https://www.cnblogs.com/zsy828/p/18420623

相关文章

  • [操作系统]线程在 Linux 中的实现
    线程在Linux中的实现线程机制是现代编程技术中常用的一种抽象概念。该机制提供了在同一程序内共享内存地址空间运行的一组线程。这些线程还可以共享打开的文件和其他资源。线程机制支持并发程序设计技术(concurrentprogramming),在多处理器系统上,它也能保证真正的并行处理(para......
  • python+Flask + vue 的博客系统
    python+Flask+vue的博客系统。系统包含源码➕数据库➕仑纹(ppt)。开发技术:Python flaskvuemysql。项目内容:博客系统设计主要有管理员和用户两个功能模块。以下将对这两个功能的作用进行详细的剖析。管理员模块:管理员是系统中的核心用户,管理员登录后,可以对后台系统进......
  • 排队论——随机服务系统仿真精解
    排队论作为研究随机服务系统的重要工具,专门研究系统中客户到达、排队、服务和离开的过程。排队论的核心目的是通过数学建模和分析,研究系统的性能指标,如平均等待时间、队列长度、系统的吞吐量等。虽然排队论提供了强大的数学工具来分析随机服务系统,但在许多复杂的实际问题中,精确的......
  • windows系统无法连接服务器
    如题所示,前几天在使用vscode连接实验室的服务器的时候出现了以下问题连接服务器报错前提是我的vscode连接正常,账户和密码输入无误且在相同环境WiFi下进行连接的(如果有人需要远程连接服务器则需使用脚本文件先在终端运行再进行连接,如下图所示运行脚本文件)1、......
  • springboot布式架构网上商城系统的设计与实现
    大家好,我是永钊,一个混迹在java圈的码农,今天要和大家聊的是一款基于springboot的大学生科创项目在线管理系统,项目源码请联系永钊,目前有各类成品毕设javawebsshssmspringboot等等项目框架,源码丰富。专业团队,咨询就送开题报告,活动限时免费,有需要的朋友可以来留言咨询。本......
  • kubeadm搭建K8S容器集群管理系统(一)
    认识各k8s各组件的作用: 1.1Kubernetes概述Kubernetes是Google开源的容器集群管理系统,基于Docker构建一个容器的调度服务,提供资源调度、均衡容灾、服务注册、动态扩缩容等功能套件。Kubernetes基于docker容器的云平台,简写成:k8s官方网站:https://kubernetes.io/官方网站非常友好,为......
  • springboot招聘信息管理系统的设计与实现
    大家好,我是永钊,一个混迹在java圈的码农,今天要和大家聊的是一款基于springboot的招聘信息管理系统,项目源码请联系永钊,目前有各类成品毕设javawebsshssmspringboot等等项目框架,源码丰富。专业团队,咨询就送开题报告,活动限时免费,有需要的朋友可以来留言咨询。本网站系统采......
  • Java基于SpringBoot的研究生导师分配双选管理系统+Vue[毕业设计]
    文末获取资源,收藏关注不迷路文章目录前言主要使用技术研究内容核心代码文章目录前言伴随着我国社会的发展,人民生活质量日益提高。于是对导师选择管理进行规范而严格是十分有必要的,所以许许多多的信息管理系统应运而生。此时单靠人力应对这些事务就显得有些力不从......
  • 计算机毕业设计 基于Python的汽车销售管理系统 Python+Django+Vue 前后端分离 附源码
    ......
  • 毕业设计选题:151基于springboot+vue的校园志愿者管理系统
     开发语言:Java框架:springbootJDK版本:JDK1.8服务器:tomcat7数据库:mysql5.7(一定要5.7版本)数据库工具:Navicat11开发软件:eclipse/myeclipse/ideaMaven包:Maven3.3.9系统展示系统首页用户注册活动信息活动心得个人中心管理员登录管理员功能志愿者管理活动类型管理......