文章

prometheus x docker部署教程

使用docker部署


FastAPI 集成 Prometheus 并用 Docker 运行 Prometheus 服务


1. 下载 Prometheus 镜像

docker pull prom/prometheus
  • 从 Docker Hub 拉取官方 Prometheus 镜像。

  • 如果本地已有,会跳过下载。


2. 创建 Prometheus 配置目录

mkdir -p ~/prometheus
  • 在当前用户家目录下创建 prometheus 文件夹。

  • 用来存放 prometheus.yml 配置文件和数据持久化目录。


3. 进入目录

cd ~/prometheus
  • 后续创建的配置文件会放在这个目录中。


4. 创建配置文件

touch prometheus.yml
  • 新建一个空的 Prometheus 配置文件。

  • 稍后会在里面写入抓取规则。


5. 编写 Prometheus 配置

编辑 prometheus.yml

global:
  scrape_interval: 15s          # 每隔 15 秒抓取一次指标
  evaluation_interval: 15s      # 每隔 15 秒评估一次规则

scrape_configs:
  # 抓取 Prometheus 自身指标
  - job_name: "prometheus-self"
    static_configs:
      - targets: ["localhost:9999"]

  # 抓取 FastAPI 应用指标
  - job_name: "my-fastapi"
    static_configs:
      - targets: ["host.docker.internal:8000"]  # 目标地址
    metrics_path: "/metrics"

配置说明:

  • scrape_interval:每个抓取目标的默认采集频率。

  • evaluation_interval:规则计算的周期(Alert/Recording Rules)。

  • job_name:任务名称,用于在 Prometheus UI 中区分。

  • targets:要采集的地址(需包含端口)。

  • metrics_path:采集路径,FastAPI 默认 /metrics

  • localhost:9999:指 Prometheus 自己监听的地址(用于自监控)。

  • host.docker.internal:Docker Desktop 环境下容器访问宿主机的域名(Linux 可能不可用,需要用宿主机 IP)。


6. 启动 Prometheus 容器

docker run -d \
  --name prometheus \
  -p 9999:9999 \
  -v ~/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro \
  -v ~/prometheus/data:/prometheus \
  prom/prometheus \
  --config.file=/etc/prometheus/prometheus.yml \
  --storage.tsdb.path=/prometheus \
  --web.listen-address=":9999" \
  --web.enable-lifecycle

参数说明:

  • -d:后台运行。

  • --name prometheus:容器名称。

  • -p 9999:9999:将容器 9999 端口映射到宿主机 9999。

  • -v ~/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro:挂载配置文件到容器内,并设为只读。

  • -v ~/prometheus/data:/prometheus:挂载数据目录,实现历史数据持久化。

  • --config.file:指定 Prometheus 配置文件路径。

  • --storage.tsdb.path:指定 TSDB 存储路径(和挂载目录一致)。

  • --web.listen-address=":9999":容器内部监听 9999 端口。

  • --web.enable-lifecycle:允许通过 HTTP 接口热加载配置。


7. 检查容器运行状态

docker ps | grep prometheus
  • 确认容器是否在运行。


8. 查看容器日志

docker logs -f prometheus
  • 实时查看 Prometheus 日志,排查配置或运行错误。


9. 测试被采集的 FastAPI 接口

curl http://host.docker.internal:8000/metrics
  • 确认 FastAPI /metrics 能返回 Prometheus 格式的指标数据。


10. 在浏览器访问 Prometheus

http://localhost:9999/
  • 打开 Prometheus Web UI。

  • 可以在 Status → Targets 中查看目标是否正常被抓取。


11. 修改配置后热重载

curl -X POST http://localhost:9999/-/reload
  • 重新加载配置文件,不用重启容器(前提是启动时加了 --web.enable-lifecycle)。


12. 常见问题

  1. 采集失败:connection refused

    • 检查 targets 地址是否正确。

    • 确认 FastAPI /metrics 可访问。

    • 确认 scheme 与服务匹配(HTTP/HTTPS)。

  2. Linux 下无法使用 host.docker.internal

    • 解决方案:

      • 用宿主机内网 IP 替代(ip addr 查看)。

      • 或使用 --network host 启动 Prometheus(仅限 Linux,注意端口冲突)。

  3. 数据丢失

    • 没有挂载 /prometheus 数据目录时,容器销毁会导致历史指标丢失。

  4. 端口冲突

    • 如果宿主机已有 9999 端口占用,可以改为 -p 9090:9090 并使用默认监听端口。


许可协议:  CC BY 4.0