.NET Core中Prometheus MetricServer端口修改失败求助
问题描述
原本可通过localhost:22990/metrics访问Prometheus指标,希望将端口修改为localhost:22300/metrics,已在Startup.cs中修改代码如下:
app.Map("/metrics", metricsApp => { metricsApp.UseMiddleware<BasicAuthMW>("Corporation"); metricsApp.UseMetricServer(22300); }); app.UseRouting(); app.UseHttpMetrics();
但Chrome提示http://localhost:22300/metrics无法连接,报错信息:
This site can’t be reachedlocalhost refused to connect. Try: Checking the connection; Checking the proxy and the firewall; ERR_CONNECTION_REFUSED
且原端口localhost:22990/metrics仍可正常访问,需解决端口修改问题。
问题原因
你的代码写法存在逻辑错误:
UseMetricServer(22300)是用来启动独立Kestrel端点提供指标服务的API,但你把它嵌套在了app.Map("/metrics")的路径分支中,导致新端口的端点无法正确加载中间件,也无法和主应用的路由逻辑兼容。- 原端口的
/metrics路径未被移除,所以仍能正常访问。
正确解决方案
提供两种可行方案,根据你的需求选择:
方案一:修改应用主端口为22300(指标路径保持/metrics)
这种方案让指标服务和应用共享同一个端口,仅修改应用的监听端口:
- 在
appsettings.json中配置Kestrel监听端口:
{ "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:22300" } } } }
- 调整
Startup.cs中的代码,移除UseMetricServer,改用UseHttpMetrics绑定到路径分支:
app.Map("/metrics", metricsApp => { metricsApp.UseMiddleware<BasicAuthMW>("Corporation"); metricsApp.UseHttpMetrics(); // 绑定指标收集到该路径 }); app.UseRouting(); // 其他应用中间件配置...
此时访问localhost:22300/metrics即可,原22990端口不再监听。
方案二:让指标服务在独立端口22300运行(主应用保留原端口)
这种方案让指标服务单独占用22300端口,主应用仍用22990端口:
调整Startup.cs中的代码,直接配置独立的指标端点,并移除原路径分支:
// 配置独立端口的指标服务,包含BasicAuth验证 app.UseMetricServer(options => { options.Port = 22300; options.Path = "/metrics"; // 为指标端点配置中间件 options.EndpointConfig = metricsApp => { metricsApp.UseMiddleware<BasicAuthMW>("Corporation"); }; }); // 移除原来的app.Map("/metrics")分支,避免原端口仍能访问指标 app.UseRouting(); app.UseHttpMetrics(); // 其他应用中间件配置...
此时访问localhost:22300/metrics即可,原22990端口无法再访问/metrics路径。
内容的提问来源于stack exchange,提问作者jrsometing
相关产品推荐
相关产品推荐

