You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确编写整合FastAPI、Prometheus、Grafana的docker-compose.yml并解决启动报错

问题解决方法

1. 解决FastAPI服务启动报错问题

报错原因是command字段的数组写法错误:当用数组格式写command时,每一个元素是独立的命令/参数,你把一整条pip命令当成了单个可执行文件传入,系统找不到对应路径的文件才会报错。
修改fastapi服务的command字段,用sh -c包裹多条连续执行的命令,同时给fastapi服务加入back-tier网络,解决后续Prometheus跨网络访问的问题:

services:
  fastapi:
    image: tiangolo/uvicorn-gunicorn-fastapi:python3.8
    ports:
        - 80:80
    volumes:
        - ./app:/app
    working_dir: /app
    # 修正command写法,用sh执行多条命令
    command: sh -c "pip install --no-cache-dir --upgrade -r requirements.txt && uvicorn app.main:app --host 0.0.0.0 --port 80"
    # 加入back-tier网络,和Prometheus互通
    networks:
      - back-tier
      - front-tier # 若需要外部直接访问服务可保留该配置
    restart: always

2. 解决Prometheus无法拉取指标问题

2.1 网络配置修正

上一步已经给fastapi服务加入了back-tier网络,同网络下的Prometheus可以直接用服务名(fastapi、node-exporter)作为域名访问对应服务,无需使用宿主机IP。

2.2 Prometheus采集配置修正

修改本地./prometheus/prometheus.yml配置,添加对应采集任务:

global:
  scrape_interval: 15s
scrape_configs:
  # 采集Prometheus自身指标
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']
  # 采集node-exporter主机指标
  - job_name: 'node-exporter'
    static_configs:
      - targets: ['node-exporter:9100']
  # 采集FastAPI应用指标
  - job_name: 'fastapi'
    static_configs:
      - targets: ['fastapi:80']

2.3 FastAPI侧指标接口配置

确保你的FastAPI应用代码中已经集成了Prometheus指标接口:

  • 在requirements.txt中添加prometheus-client依赖
  • 代码中添加/metrics端点,示例如下:
from fastapi import FastAPI
from prometheus_client import make_asgi_app, Counter

app = FastAPI()
# 挂载metrics接口
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)

# 示例自定义指标
REQUEST_COUNT = Counter("fastapi_requests_total", "总请求数统计")

@app.get("/")
def read_root():
    REQUEST_COUNT.inc()
    return {"status": "ok"}

2.4 可选优化

你当前使用的Prometheus v2.1.0是2018年的老旧版本,存在大量安全漏洞和功能缺失,建议将镜像版本升级为官方稳定版,比如prom/prometheus:v2.47.0。

验证步骤

修改完成后执行以下命令重启服务:

# 注意:-v参数会删除已创建的卷,如有历史数据请去掉该参数
docker-compose down -v
docker-compose up -d

启动完成后访问以下地址验证服务状态:

  • FastAPI指标接口:http://localhost/metrics 确认返回指标数据
  • Prometheus后台:http://localhost:9090/targets 确认所有采集目标状态为UP
  • Grafana后台:http://localhost:3000 配置Prometheus数据源后即可搭建监控面板

内容的提问来源于stack exchange,提问作者Gelder Das Geld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:27:05