用 Prometheus 監控 Node.js 應用程式
抓取 Express 執行環境與 HTTP 指標,用 PromQL 查請求速率、5xx 比例和 P95,並設定考量低流量情況的告警。
結帳 API 開始回傳 503,CPU 和堆積記憶體卻看起來正常。這時要先知道有多少請求失敗,以及已完成的回應整體是否變慢。Node.js 的 Prometheus 用戶端可從同一個 /metrics 端點提供執行環境指標,以及你為這兩個問題加上的計數器與直方圖。
下文以一條 Express 路由為例,從記錄指標、設定 Prometheus 抓取,到定義兩條告警規則。結帳結果為示範資料。
讓 Prometheus 抓取應用程式指標
Prometheus 定期向應用程式抓取指標。指標名稱與一組標籤共同識別一條時間序列,每次成功抓取都會加入新的樣本。Prometheus 執行 PromQL 查詢並評估告警規則,Alertmanager 負責將通知傳送到對應管道,Grafana 則能將資料視覺化。
專案原本以 prom-client 為套件名稱。本例使用後繼套件 @prometheus-io/client 0.16.1 和 Node.js 22。這個套件版本支援 Node.js 22、24、26 及更新版本。請在獨立的測試專案安裝依賴。
npm install express@5.3.0 @prometheus-io/client@0.16.1
將以下程式存為 checkout.cjs,執行 node checkout.cjs。範例只在本機回送介面監聽。部署時,要讓收集器能從受控的網路路徑存取 /metrics,並限制其他來源的存取。
const express = require('express');
const client = require('@prometheus-io/client');
const app = express();
client.collectDefaultMetrics();
const requests = new client.Counter({
name: 'http_requests_total',
help: 'Completed checkout HTTP responses',
labelNames: ['method', 'route', 'status'],
});
const inFlight = new client.Gauge({
name: 'http_requests_in_flight',
help: 'Checkout HTTP responses still in progress',
});
const duration = new client.Histogram({
name: 'request_duration_seconds',
help: 'Completed checkout response duration in seconds',
labelNames: ['route'],
buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5],
});
app.get('/metrics', async (req, res) => {
res.set('Content-Type', client.register.contentType);
res.end(await client.register.metrics());
});
const checkoutRoute = '/checkout';
for (const status of ['204', '503']) {
requests.inc({ method: 'POST', route: checkoutRoute, status }, 0);
}
app.post(checkoutRoute, (req, res) => {
const route = checkoutRoute;
const stopTimer = duration.startTimer({ route });
inFlight.inc();
res.once('finish', () => {
requests.inc({ method: req.method, route, status: String(res.statusCode) });
stopTimer();
});
res.once('close', () => inFlight.dec());
res.status(req.query.fail === '1' ? 503 : 204).end();
});
app.listen(3000, '127.0.0.1');
curl -i -X POST 'http://127.0.0.1:3000/checkout'
curl -i -X POST 'http://127.0.0.1:3000/checkout?fail=1'
curl -fsS http://127.0.0.1:3000/metrics
兩次請求分別回傳 204 與 503,查詢參數只用來模擬失敗。接著抓取指標,http_requests_total 會出現兩個狀態碼,request_duration_seconds_count 則記下兩個已完成的觀測值。預設指標包含事件迴圈延遲、垃圾回收、堆積記憶體與 CPU 等訊號,部分項目會因作業系統而異。
依你要回答的問題選指標
**計數器(Counter)**記錄已完成的回應,依方法、路由與狀態區分。程序重新啟動時,計數會重設。在回應的 finish 事件讀取最終狀態碼。此事件代表資料交由作業系統傳送,因此範例量到的是從路由處理開始的伺服器端時間,未涵蓋用戶端網路耗時。
**量表(Gauge)**記錄尚在處理的回應。處理函式開始時加一,收到 close 時減一,即使連線提早終止也會扣回。未到達 finish 的中斷回應不計入已完成數量或延遲直方圖。如果業務在意連線中斷,可另行計數。
**傳統直方圖(Histogram)**把耗時記進累計的時間區間。多個副本使用相同的區間邊界時,Prometheus 可以合併計數後再估算分位數。建議在關注的延遲門檻附近設邊界。**摘要(Summary)**可在應用程式內算出每個程序的分位數。各程序的 P95 取平均,無法得到整體請求的 P95。
控制標籤的值域。以 /orders/:id 來說,使用路由樣板當標籤,別把訂單 ID 或原始查詢字串放進去。每組不同的標籤都會新增時間序列,直方圖還會為每個區間、總和與計數分別建立序列。
查請求速率、錯誤比例和 P95
將下列設定存為 prometheus.yml,把下一節的告警檔放在同一個目錄,然後在與範例相同的主機執行 prometheus --config.file=prometheus.yml。
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- checkout-alerts.yml
scrape_configs:
- job_name: checkout-node
static_configs:
- targets: ["127.0.0.1:3000"]
第一條查詢回傳各路由每秒完成的回應數,第二條計算結帳抓取工作中 5xx 回應的百分比,第三條以秒為單位估算各路由的 P95。
sum by (route) (rate(http_requests_total{job="checkout-node"}[5m]))
100 * (
sum(rate(http_requests_total{job="checkout-node",status=~"5.."}[5m]))
or 0 * sum(rate(http_requests_total{job="checkout-node"}[5m]))
) / (sum(rate(http_requests_total{job="checkout-node"}[5m])) > 0)
histogram_quantile(0.95, sum by (le, route) (
rate(request_duration_seconds_bucket{job="checkout-node"}[5m])
))
先對各條計數器序列執行 rate(),再彙總,Prometheus 才能辨識各程序重新啟動造成的重設。有可計算的流量但沒有可用的 5xx 速率時,or 0 * ... 會把分子補為零。新序列要累積足夠的樣本才能計算速率。範例先初始化兩種已知狀態碼的計數器,讓收集器能在第一次錯誤前抓到零值。若沒有流量或缺少有效的總速率,分母條件會讓結果保持空白。另看 up,才能區分沒有請求與抓取失敗。
讓持續的異常觸發告警
checkout-alerts.yml 以最近五分鐘的資料計算,條件在規則評估中持續成立五分鐘才會觸發。範例也設定最低請求速率,避免極少量請求觸發這組門檻。依流量和 SLO 調整門檻,並在 Prometheus 設定 Alertmanager 目標來傳送通知。
groups:
- name: checkout
rules:
- record: checkout:http_requests_per_second:rate5m
expr: sum(rate(http_requests_total{job="checkout-node"}[5m]))
- alert: CheckoutHighErrorRatio
expr: |
(
sum(rate(http_requests_total{job="checkout-node",status=~"5.."}[5m]))
or 0 * checkout:http_requests_per_second:rate5m
) / checkout:http_requests_per_second:rate5m > 0.01
and checkout:http_requests_per_second:rate5m > 0.2
for: 5m
- alert: CheckoutHighP95
expr: |
histogram_quantile(0.95, sum by (le) (
rate(request_duration_seconds_bucket{job="checkout-node"}[5m])
)) > 2
and checkout:http_requests_per_second:rate5m > 0.2
for: 5m
讓觀測雲使用同一個端點
DataKit 的 Prom 收集器可抓取既有的 /metrics,並將選取的指標送到觀測雲。設定目標、所需的驗證方式和抓取週期,建立錯誤率或延遲監控器前,先核對指標型別、單位與標籤對應。若想從延遲告警往下查追蹤,需要另外接入 Node.js APM。若要從 span 跳到日誌,還要將 trace ID 和 span ID 注入日誌,並讓服務、環境與版本欄位和追蹤端一致。
部署時的常見問題
多個副本或 Node.js worker 怎麼抓?
讓每個副本都有可分別抓取的目標。只抓一個負載平衡端點,每次可能取得不同程序的資料。使用 Node.js cluster 時,可分別暴露各 worker,也可用用戶端的 AggregatorRegistry 統計。Kubernetes 若已安裝 Prometheus Operator,可讓選取器與連接埠正確對應,再透過 ServiceMonitor 探索端點。
CronJob 在兩次抓取之間就結束了,怎麼辦?
和特定機器無關的服務層批次工作,可將執行結果或上次成功時間送到 Pushgateway,再由 Prometheus 或 DataKit 抓取。Pushgateway 會保留群組直到明確刪除,因此要在工作移除時清理。綁定特定機器的工作可評估 Node Exporter 的 textfile collector。若要逐次保留執行記錄,可用日誌或追蹤。
加上指標會多花多少資源?
用實際流量量測。指標數量、不同標籤組合數、直方圖區間數與抓取頻率都影響收集成本和傳輸大小。使用者 ID 這類高基數標籤,也會增加後端儲存和查詢的序列數。
參考資料
- Node.js 的 Prometheus 用戶端與變更紀錄
- Prometheus 直方圖與摘要及埋點實務
- Prometheus 告警規則及 Pushgateway 使用時機
- Node.js HTTP 回應事件及 Prometheus Operator 設定
