如何将树莓派温度传感器文本数据接入Docker部署的Prometheus?
将树莓派温度传感器文本数据接入Prometheus的方法
1. 转换温度数据为Prometheus兼容格式
Prometheus仅识别指标名 数值的标准metrics格式,需先把你的温度文本转换成该格式。以下以提取最新温度值为例:
- 编写bash转换脚本(也可使用Python等其他语言):
#!/bin/bash # 替换为你的温度文件实际路径 TEMP_FILE="/home/pi/temperature.log" # 替换为后续node_exporter的textfile收集目录 OUTPUT_FILE="/var/lib/node_exporter/textfile_collector/temp.prom" # 跳过表头,提取最后一行温度值并生成标准metrics格式 tail -n +2 "$TEMP_FILE" | awk -F ', ' '{print "raspberrypi_temperature_celsius " $2}' > "$OUTPUT_FILE" - 给脚本添加执行权限:
chmod +x /home/pi/convert_temp.sh - 用crontab定时更新metrics文件(比如每5分钟执行一次):
crontab -e # 在打开的文件中添加以下内容 */5 * * * * /home/pi/convert_temp.sh
2. 在树莓派部署node_exporter(暴露自定义指标)
node_exporter是Prometheus官方工具,支持通过textfile目录收集自定义指标。用Docker部署的命令如下:
docker run -d \ --name node_exporter \ --net="host" \ --pid="host" \ -v "/:/host:ro,rslave" \ -v "/var/lib/node_exporter/textfile_collector:/var/lib/node_exporter/textfile_collector" \ quay.io/prometheus/node-exporter:latest \ --path.rootfs=/host \ --collector.textfile.directory=/var/lib/node_exporter/textfile_collector
验证:访问http://<树莓派IP>:9100/metrics,搜索raspberrypi_temperature_celsius,确认能看到该指标条目。
3. 配置Prometheus抓取树莓派指标
修改你的Prometheus配置文件(如prometheus.yml),新增抓取任务:
scrape_configs: # 保留原有配置,新增以下内容 - job_name: 'raspberrypi_temp' static_configs: - targets: ['<树莓派IP>:9100']
重启Prometheus容器生效:
docker restart prometheus
验证:在Prometheus UI的Graph页面,搜索raspberrypi_temperature_celsius,确认能查询到温度数据。
4. 在Grafana中可视化温度数据
- 若未添加Prometheus数据源,进入Grafana的
Configuration > Data sources,选择Prometheus并填写你的Prometheus服务地址完成添加 - 创建新仪表盘,添加面板,在查询框输入
raspberrypi_temperature_celsius,选择折线图等合适的图表类型,调整显示样式后保存仪表盘。
内容的提问来源于stack exchange,提问作者user1631385
相关产品推荐
相关产品推荐

