匠心精神 - 良心品质腾讯认可的专业机构-IT人的高薪实战学院

咨询电话:4000806560

从部署到监控:快速搭建自己的 Prometheus 监控系统

从部署到监控:快速搭建自己的 Prometheus 监控系统

随着互联网技术的发展,监控系统越来越重要。在一次紧急排查中,我发现我们的系统没有监控,导致难以分析问题。因此,我学习了一下 Prometheus 监控系统,并写下这篇文章以帮助需要的人快速搭建自己的监控系统。

什么是 Prometheus?

Prometheus 是一款开源的监控系统。它的特点是易于部署、易于操作、易于扩展、支持多维度数据收集和灵活的查询语言。从架构上来说,它采用 pull 模型,不需要使用者编写采集指标的代码。另外,Prometheus 社区提供了一些 Exporter,用于采集各类应用和设备的数据。最后,Prometheus 提供了一些可视化工具,如 Grafana 和 Alertmanager。

如何部署 Prometheus?

Prometheus 可以在各种环境中运行,如 Docker、Kubernetes 和虚拟机。但为了保持简洁,这篇文章只介绍基于 Docker 和 Docker Compose 的部署方式。

首先,你需要在你的机器上安装 Docker 和 Docker Compose。然后,你需要创建一个 Docker Compose 文件,如下所示:

version: '3'

services:
  prometheus:
    image: prom/prometheus:v2.23.0
    container_name: prometheus
    restart: always
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
    command:
      - --config.file=/etc/prometheus/prometheus.yml

上述配置文件中,我们使用了官方提供的 Prometheus 镜像,并将镜像暴露在 9090 端口。我们还将它的配置文件挂载到了我们本地目录中。在该配置文件中,你需要指定你要采集的应用或设备的 Exporter 的地址。

为了启动该服务,你只需在该 Docker Compose 文件所在目录下运行以下命令:

$ docker-compose up -d

如何配置 Exporter?

在 Prometheus 的配置文件中,你需要指定你要采集的 Exporter 的地址。在本文中,我们以 Node Exporter 为例。Node Exporter 是一个针对 Linux 系统的 Exporter,用于采集系统级别的指标。

使用以下命令下载 Node Exporter:

$ wget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz

解压文件并启动 Node Exporter:

$ tar -xvf node_exporter-1.2.2.linux-amd64.tar.gz
$ cd node_exporter-1.2.2.linux-amd64
$ ./node_exporter

现在,你可以在 Prometheus 的配置文件中添加以下内容:

- job_name: 'node_exporter'
  static_configs:
    - targets: ['localhost:9100']

上述内容中,我们使用了 static_configs 类型,指定了要采集的主机的地址。

如何查询指标?

Prometheus 使用 PromQL 语言进行查询。以下是一些常见的查询:

- 查询 CPU 使用率:`100 - (avg by(instance)(irate(node_cpu_seconds_total{mode='idle'}[5m])) * 100)`
- 查询内存使用率:`(node_memory_MemTotal - node_memory_MemFree - node_memory_Buffers - node_memory_Cached) / node_memory_MemTotal * 100`
- 查询磁盘使用率:`(node_filesystem_size_bytes - node_filesystem_free_bytes) / node_filesystem_size_bytes * 100`

如何可视化?

Prometheus 提供了一些可视化工具,如 Grafana 和 Alertmanager。这里,我们以 Grafana 为例,展示如何使用该工具来可视化指标。

首先,你需要下载 Grafana:

$ docker run -d --name=grafana -p 3000:3000 grafana/grafana

然后,你需要在 Grafana 的界面中添加 Prometheus 数据源,并创建一个 Dashboard。你可以使用上述查询语言来创建 Panel,并使用 Prometheus 的标签来进行聚合。

最后,你可以使用 Alertmanager 来发送报警并集成到你的监控系统中。

结论

在本文中,我们介绍了如何快速搭建自己的 Prometheus 监控系统,并展示了如何配置 Exporter、查询指标和可视化数据。如果你在使用 Prometheus 时遇到了问题,请到官方文档中查找帮助或联系社区成员。