Prometheus开源项目解析:Azure VM环境配置与开发实践

云信安装大师
90
AI 质量分
10 5 月, 2025
3 分钟阅读
0 阅读

Prometheus开源项目解析:Azure VM环境配置与开发实践

引言

Prometheus作为云原生时代最流行的监控系统之一,已经成为DevOps和SRE工程师的必备工具。本文将带你在Azure虚拟机上从零开始搭建Prometheus监控系统,并通过实际案例演示如何开发自定义exporter。

准备工作

在开始之前,你需要:

  1. 一个有效的Azure账号
  2. 基本的Linux命令行知识
  3. 了解HTTP协议基础概念

第一步:创建Azure虚拟机

代码片段
# 登录Azure CLI
az login

# 创建资源组(替换<your-resource-group>和<location>)
az group create --name <your-resource-group> --location eastus

# 创建VM(替换<your-vm-name>)
az vm create \
    --resource-group <your-resource-group> \
    --name <your-vm-name> \
    --image UbuntuLTS \
    --admin-username azureuser \
    --generate-ssh-keys \
    --size Standard_B1s

参数说明
--image UbuntuLTS:使用Ubuntu长期支持版作为操作系统
--size Standard_B1s:选择性价比高的B1s机型(1vCPU,1GB内存)
--generate-ssh-keys:自动生成SSH密钥对

注意事项
1. 生产环境建议选择至少2vCPU和4GB内存的机型
2. 记录命令输出的publicIpAddress,用于后续SSH连接

第二步:连接到VM并安装Prometheus

代码片段
# SSH连接到VM(替换<publicIpAddress>)
ssh azureuser@<publicIpAddress>

# 更新系统包
sudo apt update && sudo apt upgrade -y

# 下载最新版Prometheus(请检查官网获取最新版本号)
wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz

# 解压文件
tar xvfz prometheus-*.tar.gz

# 移动到标准目录
cd prometheus-*
sudo mv prometheus promtool /usr/local/bin/
sudo mkdir -p /etc/prometheus
sudo mv prometheus.yml /etc/prometheus/

原理说明
1. Prometheus采用Go编写,直接提供预编译二进制文件
2. /etc/prometheus目录存放配置文件
3. /usr/local/bin存放可执行文件是Linux的常见做法

第三步:配置Prometheus服务

创建systemd服务文件:

代码片段
sudo nano /etc/systemd/system/prometheus.service

添加以下内容:

代码片段
[Unit]
Description=Prometheus Server
Documentation=https://prometheus.io/docs/introduction/overview/
After=network-online.target

[Service]
User=prometheus
Restart=on-failure
ExecStart=/usr/local/bin/prometheus \
    --config.file=/etc/prometheus/prometheus.yml \
    --storage.tsdb.path=/var/lib/prometheus/data \
    --web.console.templates=/etc/prometheus/consoles \
    --web.console.libraries=/etc/prometheus/console_libraries \
    --web.listen-address=0.0.0.0:9090

[Install]
WantedBy=multi-user.target

设置权限并启动服务:

代码片段
# 创建专用用户和数据目录
sudo useradd -rs /bin/false prometheus
sudo mkdir /var/lib/prometheus/data
sudo chown prometheus:prometheus /var/lib/prometheus/data

# 重新加载systemd并启动服务
sudo systemctl daemon-reload
sudo systemctl start prometheus
sudo systemctl enable prometheus

# 检查状态(应显示active (running))
sudo systemctl status prometheus

实践经验
1. --web.listen-address=0.0.0.0:9090确保可以从外部访问Web界面
2. Promethues默认使用端口9090,确保Azure网络安全组已开放该端口
3. TSDB存储路径应放在有足够空间的磁盘分区上

第四步:配置Azure网络安全组

代码片段
# 允许9090端口入站(替换<your-resource-group>)
az network nsg rule create \ 
    --resource-group <your-resource-group> \ 
    --nsg-name <your-vm-name>NSG \ 
    --name allow-prom \ 
    --access Allow \ 
    --protocol Tcp \ 
    --direction Inbound \ 
    --priority 100 \ 
    --source-port-range "*" \ 
    --destination-port-range 9090 

现在可以通过浏览器访问 http://<publicIpAddress>:9090查看Promethues Web UI。

第五步:开发自定义Exporter实践

让我们创建一个简单的Node.js exporter来监控自定义应用指标:

代码片段
// custom-exporter.js - Node.js自定义Exporter示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例代码示例码码码码码码码码码码码码码码码码码码码码const express = require('express');
const client = require('prom-client');

const app = express();
const port = 9100;

// Create a Registry which registers the metrics client.register = new client.Registry();

// Add a default label which is added to all metrics client.register.setDefaultLabels({ app: 'custom-exporter' });

// Enable the collection of default metrics client.collectDefaultMetrics({ register: client.register });

// Create a custom metric const customMetric = new client.Gauge({
 name: 'custom_metric',
 help: 'This is a custom metric example',
 labelNames: ['endpoint'],
});

// Add the custom metric to the registry client.register.registerMetric(customMetric);

// Update metric value every second setInterval(() => {
 customMetric.set({ endpoint: '/api' }, Math.random() *100);
},1000);

// Expose the metrics endpoint app.get('/metrics', async (req, res) => {
 res.set('Content-Type', client.register.contentType);
 res.end(await client.register.metrics());
});

app.listen(port, () => {
 console.log(`Custom exporter listening at http://localhost:${port}`);
});

安装依赖并运行:

bashnpm install express prom-client node app.js

在Promethues配置中添加这个exporter:

“`yaml # /etc/Promethues/Promethues.yml scrapeconfigs:
– job
name: ‘custom-exporter’
static_configs:
– targets: [‘localhost:9100’]
labels:
service: ‘custom-service’

代码片段

重载Promethues配置:

```bash sudo systemctl reload Promethues

常见问题解决 Q1:无法访问Web界面 •检查Azure网络安全组规则 •确认VM本地防火墙设置( sudo ufw allow9090/tcp) Q2:指标收集失败 •检查exporter是否运行( netstat-tulnp | grep9100) •查看Promethues日志( journalctl-u Promethues-f)

总结本文详细介绍了在Azure VM上部署Promethues的全过程,包括:1.Azure VM创建与网络配置2.Promethues二进制安装与systemd服务配置3.Azure网络安全组设置4.自定义exporter开发实践关键点:•生产环境建议将数据目录挂载到独立磁盘•使用–storage.tsdb。retention.time调整数据保留时间•考虑使用Grafana进行可视化展示下一步可以探索Alertmanager告警配置和Grafana集成。

原创 高质量