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

如何在独立端口暴露Strapi Prometheus指标并移除api前缀

实现方案

方案1:用独立Node服务转发指标(推荐)

由于Strapi官方Prometheus插件没有直接配置指标端口的选项,你可以快速搭建一个轻量的Node HTTP服务,专门在9090端口暴露/metrics路径,内部转发请求到Strapi的原有指标接口,不用改动Strapi核心配置。

步骤如下:

  1. 新建一个文件(比如metrics-server.js),写入以下原生Node代码(无需额外依赖):
const http = require('http');

const strapiMetricsUrl = 'http://localhost:1337/api/metrics';
const metricsPort = 9090;

const server = http.createServer((req, res) => {
  if (req.url === '/metrics') {
    // 解析Strapi指标接口的地址信息
    const url = new URL(strapiMetricsUrl);
    const proxyOptions = {
      hostname: url.hostname,
      port: url.port,
      path: url.pathname,
      method: 'GET'
    };

    // 转发请求到Strapi
    const proxyReq = http.request(proxyOptions, (proxyRes) => {
      res.writeHead(proxyRes.statusCode, proxyRes.headers);
      proxyRes.pipe(res);
    });

    proxyReq.on('error', (err) => {
      res.writeHead(500);
      res.end(`获取指标失败: ${err.message}`);
    });

    proxyReq.end();
  } else {
    res.writeHead(404);
    res.end('404 Not Found');
  }
});

server.listen(metricsPort, () => {
  console.log(`指标服务运行在 http://localhost:${metricsPort}/metrics`);
});
  1. 运行该服务:node metrics-server.js,如果需要后台持续运行,可以用pm2或nohup管理进程。

方案2:用反向代理(如Nginx)

如果你的部署环境已有Nginx,可通过配置反向代理实现需求:

  1. 编辑Nginx配置文件,添加以下规则:
server {
  listen 9090;
  server_name localhost;

  location /metrics {
    proxy_pass http://localhost:1337/api/metrics;
    proxy_set_header Host $host;
  }
}
  1. 重启Nginx服务,之后访问http://localhost:9090/metrics即可获取Strapi指标。

方案3:修改插件源码(不推荐)

这种方式需要改动Strapi插件的核心代码,插件升级后修改会丢失,仅作为临时应急方案:

  1. 找到插件安装目录(通常在node_modules/@strapi/plugin-prometheus)
  2. 修改server/routes/metrics.js,将路由路径从/api/metrics改为/metrics
  3. 在server/bootstrap.js中新增逻辑,启动一个监听9090端口的HTTP服务器,并挂载插件的指标路由。

内容的提问来源于stack exchange,提问作者Daniela Barbosa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:54:19