如何修改prometheus-client的metrics端口?Rails应用保留默认3000端口
你可以通过以下几种方式将/metrics端点迁移到独立端口,同时保持Rails应用在3000端口运行:
方案一:使用独立的Metrics导出器进程(推荐)
这种方式将Metrics服务与Rails应用完全隔离,即使Rails进程异常,Metrics仍可正常提供数据,适合生产环境。
步骤1:配置Rails应用的Prometheus指标
在config/initializers/prometheus.rb中初始化全局Registry,并确保所有指标都注册到这里:
require 'prometheus/client' # 初始化全局指标注册表 Prometheus::Client.registry # 示例:定义一个请求计数指标 $http_requests_total = Prometheus::Client::Counter.new( :http_requests_total, docstring: 'Total number of HTTP requests handled by the app' ) Prometheus::Client.registry.register($http_requests_total) # 在控制器中使用指标(比如ApplicationController) # after_action do # $http_requests_total.increment(labels: { path: request.path, method: request.method }) # end
步骤2:创建独立的Metrics导出脚本
在项目根目录新建metrics_exporter.rb,启动一个单独的Rack服务在指定端口(比如9394):
require 'prometheus/client' require 'prometheus/client/rack/collector' require 'prometheus/client/rack/exporter' # 复用Rails的全局指标注册表 registry = Prometheus::Client.registry # 构建仅处理Metrics的Rack应用 app = Rack::Builder.new do use Prometheus::Client::Rack::Collector run Prometheus::Client::Rack::Exporter.new(registry: registry) end.to_app # 启动WEBrick服务器,监听9394端口 Rack::Handler::WEBrick.run app, Port: 9394, AccessLog: []
步骤3:启动服务
- 先启动Rails应用:
rails s -p 3000 - 再启动Metrics导出器:
ruby metrics_exporter.rb
之后Prometheus就可以通过http://localhost:9394/metrics拉取指标了。
多进程场景适配(比如Puma集群)
如果你的Rails用了多进程模式,每个进程的指标会分散,需要用Redis做集中存储。修改config/initializers/prometheus.rb:
require 'prometheus/client' require 'prometheus/client/storage/redis' # 配置Redis作为指标存储后端 Prometheus::Client.configure do |config| config.storage = Prometheus::Client::Storage::Redis.new(url: 'redis://localhost:6379/0') end # 后续指标定义和之前一致
导出脚本也会自动从Redis读取汇总后的指标,无需额外修改。
方案二:让Puma同时监听两个端口
这种方式无需额外进程,让Rails的Puma服务器同时监听3000(业务请求)和指定端口(仅处理Metrics)。
修改config/puma.rb:
# 监听业务端口3000 port 3000 # 监听Metrics端口9394 bind 'tcp://0.0.0.0:9394' # 根据端口分发请求 app do |env| if env['SERVER_PORT'] == '9394' # 仅处理Metrics请求 require 'prometheus/client/rack/exporter' Prometheus::Client::Rack::Exporter.new.call(env) else # 处理正常的Rails业务请求 Rails.application.call(env) end end
启动Puma后,访问http://localhost:9394/metrics即可获取指标,业务请求仍走3000端口。
缺点:如果Rails进程崩溃,Metrics服务也会中断,适合开发或测试环境。
方案三:用反向代理分流(适合已有Nginx的场景)
如果你的Rails应用已经在Nginx反向代理后运行,可以配置Nginx将/metrics请求转发到独立的Metrics导出端口(比如方案一中的9394),业务请求继续转发到3000端口。
示例Nginx配置片段:
server { listen 80; server_name your-app-domain.com; # 业务请求转发到Rails 3000端口 location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # Metrics请求转发到独立的9394端口 location /metrics { proxy_pass http://localhost:9394; } }
这样外部用户访问/metrics时,Nginx会自动转发到导出器端口,无需修改Rails应用的路由。
内容的提问来源于stack exchange,提问作者Jagadish

