Prometheus镜像安装与配置心得
随着容器技术的飞速发展,Docker 和 Kubernetes 等容器编排工具已经成为了企业级应用开发的热门选择。而 Prometheus 作为一款开源的监控和报警工具,能够为容器化应用提供强大的监控支持。本文将详细介绍 Prometheus 镜像的安装与配置,帮助您快速上手并应用于实际项目中。
一、Prometheus 简介
Prometheus 是一款开源的监控和报警工具,由 SoundCloud 团队开发,现已成为 Cloud Native Computing Foundation 的项目之一。它通过抓取目标上的指标数据,存储在本地时间序列数据库中,并可以通过用户自定义的规则进行报警。
二、Prometheus 镜像安装
选择合适的镜像
Prometheus 官方提供了官方镜像,地址为
docker.io/prometheus/prometheus
。您可以根据需要选择不同的版本,如latest
、2.16.0
等。拉取镜像
使用以下命令拉取 Prometheus 镜像:
docker pull docker.io/prometheus/prometheus:latest
运行容器
使用以下命令运行 Prometheus 容器:
docker run -d \
--name prometheus \
-p 9090:9090 \
-v /etc/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \
prometheus/prometheus:latest
其中,
-p 9090:9090
将容器的 9090 端口映射到宿主机的 9090 端口,-v /etc/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
将宿主机的 Prometheus 配置文件挂载到容器中。
三、Prometheus 配置
Prometheus 的配置文件位于 /etc/prometheus/prometheus.yml
,以下是配置文件的基本结构:
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
1. global 配置
scrape_interval
:抓取指标数据的间隔时间,默认为 15 秒。evaluation_interval
:执行规则计算的间隔时间,默认为 15 秒。
2. scrape_configs 配置
job_name
:抓取指标任务的名称。static_configs
:静态配置,包含目标地址列表。
四、Prometheus 监控案例
以下是一个简单的 Prometheus 监控案例,监控宿主机的 CPU 使用率:
添加指标
在 Prometheus 配置文件中添加以下指标:
scrape_configs:
- job_name: 'cpu'
static_configs:
- targets: ['localhost:9090']
metrics_path: '/metrics'
params:
metric: ['cpu_usage']
其中,
cpu_usage
是自定义指标,需要您在目标主机上实现。目标主机添加指标
在目标主机上,添加以下指标:
echo 'export cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk "{print 100 - $1}")' > /usr/local/bin/cpu_usage
chmod +x /usr/local/bin/cpu_usage
重启 Prometheus
重启 Prometheus 容器,使配置生效。
查看指标
使用以下命令查看 CPU 使用率指标:
curl http://localhost:9090/metrics | grep cpu_usage
您将看到类似以下输出:
cpu_usage 100.0
五、总结
本文详细介绍了 Prometheus 镜像的安装与配置,并通过一个简单的案例展示了 Prometheus 的监控能力。在实际应用中,您可以根据需求自定义指标和报警规则,为您的应用提供强大的监控支持。
猜你喜欢:OpenTelemetry