如何用Prometheus+Python采集不同Docker容器的自定义指标?
如何为Prometheus添加非FastAPI容器的自定义指标采集目标
核心思路很直接:先让你的非FastAPI应用把自定义指标通过HTTP端点暴露出来,再给Prometheus配置新增一个采集作业,只抓取你需要的自定义指标,过滤掉无关的系统指标。
第一步:让非FastAPI容器暴露自定义指标
如果你的目标应用(比如普通Python脚本、Go服务、Shell驱动的任务等)还没做指标暴露:
- 选轻量的客户端库:Python用
prometheus-client,Go用官方的prometheus/client_golang,其他语言也有对应的Prometheus适配库 - 在应用里定义好自定义指标(计数器、Gauge、直方图都行),再启动一个极简HTTP服务提供
/metrics端点
举个Python极简示例:from prometheus_client import start_http_server, Counter # 自定义计数器:统计非FastAPI应用的任务处理次数 custom_task_processed_total = Counter('custom_task_processed_total', 'Total tasks processed by non-FastAPI app') def run_business_task(): # 你的业务逻辑代码 custom_task_processed_total.inc() if __name__ == '__main__': # 启动HTTP服务,端口选不冲突的,比如9091 start_http_server(9091) # 模拟业务循环 while True: run_business_task() - 部署容器时,确保暴露的端口(如9091)在Docker网络里能被Prometheus访问——可以用Docker Compose同网络、端口映射,或者K8s服务发现(对应环境)
第二步:修改Prometheus配置,新增采集作业
打开Prometheus配置文件(通常是prometheus.yml),在scrape_configs下新增专门的采集作业,只保留你需要的自定义指标:
scrape_configs: # 原FastAPI应用的采集配置 - job_name: 'fastapi_app' static_configs: - targets: ['fastapi-service:8000'] # 替换为你的FastAPI容器地址/端口 # 新增的非FastAPI自定义指标采集作业 - job_name: 'custom_non_fastapi_job' static_configs: - targets: ['custom-app-service:9091'] # 替换为你的自定义应用容器地址/端口 # 过滤非自定义指标,只保留指定项 metric_relabel_configs: - source_labels: [__name__] regex: 'custom_task_processed_total|custom_queue_size' # 替换为你的自定义指标名,多指标用|分隔 # 也可以用前缀匹配所有自定义指标:regex: 'custom_.*' action: keep
metric_relabel_configs是关键:采集后会过滤掉不符合正则的指标,直接剔除系统默认指标(比如Python的process_*系列)
第三步:验证配置并生效
- 检查配置语法:Docker部署的话运行
docker exec <prometheus-container-name> promtool check config /etc/prometheus/prometheus.yml,直接部署的话用promtool check config prometheus.yml - 重启Prometheus容器,让新配置生效
- 打开Prometheus UI(默认
http://<prometheus-ip>:9090),在Targets页确认新作业状态为UP,再到Graph页搜索自定义指标,确认数据正常采集
内容的提问来源于stack exchange,提问作者Alex Poloz
相关产品推荐
相关产品推荐

