Giám sát với Prometheus và Grafana
Bài trước kết thúc ở một giới hạn: metrics-server chỉ biết hiện tại. Bài này dựng hệ thống giám sát thật cho cluster hoc-k8s: Prometheus thu và lưu metrics theo thời gian, Alertmanager gửi cảnh báo, Grafana vẽ dashboard. Bạn sẽ hiểu mô hình dữ liệu của Prometheus, viết các truy vấn PromQL quan trọng nhất, cài kube-prometheus-stack bằng Helm, gắn đo lường cho notes-api bằng prom-client, khai báo ServiceMonitor và PrometheusRule, rồi đọc dashboard có sẵn.
Vì sao cần
Những câu hỏi sau kubectl top không trả lời được:
- "p95 độ trễ của
POST /notestuần này so với tuần trước thế nào?" - "Pod notes-api có bị CPU throttling (bóp CPU vì chạm limit, chương 9) vào giờ cao điểm không?"
- "Lúc 2 giờ sáng ai đó cần được đánh thức nếu notes-api trả lỗi 5xx quá 5% trong 10 phút."
- "Memory của postgres tăng đều mỗi ngày, bao giờ thì chạm limit?"
Chúng cần ba thứ: lưu số liệu theo thời gian, ngôn ngữ truy vấn để tính toán trên chuỗi số liệu, và cảnh báo tự động. Ở Docker một máy, bạn có thể sống với docker stats và vài script; với hàng chục Pod sinh ra rồi mất đi liên tục thì không. Prometheus (dự án CNCF thứ hai sau Kubernetes) là tiêu chuẩn thực tế cho việc này, và hầu hết thành phần Kubernetes đều xuất metrics theo định dạng của nó.
Cơ chế
Mô hình Prometheus: kéo, chuỗi thời gian và label
Prometheus kéo (pull, còn gọi scrape) số liệu: cứ mỗi khoảng scrape_interval (thường 15–30 giây), nó gửi HTTP GET tới endpoint /metrics của từng target và lưu kết quả vào cơ sở dữ liệu chuỗi thời gian (time series database) của mình.
Nội dung /metrics là văn bản thuần, mỗi dòng một mẫu:
# HELP http_request_duration_seconds Thời gian xử lý request HTTP
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.05",method="GET",route="/notes",status_code="200"} 1520
http_request_duration_seconds_bucket{le="0.1",method="GET",route="/notes",status_code="200"} 1587
http_request_duration_seconds_bucket{le="+Inf",method="GET",route="/notes",status_code="200"} 1590
http_request_duration_seconds_sum{method="GET",route="/notes",status_code="200"} 41.7
http_request_duration_seconds_count{method="GET",route="/notes",status_code="200"} 1590Một chuỗi thời gian (time series) được định danh bởi tên metric + tập label. {method="GET",route="/notes",status_code="200"} và {...status_code="500"} là hai chuỗi khác nhau. Label là sức mạnh (lọc, gom nhóm thoải mái) nhưng cũng là bẫy: mỗi giá trị label mới sinh thêm chuỗi, nên không bao giờ dùng user id hay URL thô làm label.
Bốn loại metric:
| Loại | Ý nghĩa | Ví dụ |
|---|---|---|
| Counter | Chỉ tăng (về 0 khi tiến trình khởi động lại) | Tổng số request, tổng giây CPU đã dùng |
| Gauge | Lên xuống tự do | Bộ nhớ đang dùng, số Pod đang chạy |
| Histogram | Đếm quan sát theo các "xô" (le = nhỏ hơn hoặc bằng) | Độ trễ request |
| Summary | Phân vị tính sẵn ở phía ứng dụng, không gộp được giữa các Pod | Ít dùng trên Kubernetes |
Exporter là chương trình dịch số liệu của hệ thống khác sang định dạng Prometheus: node-exporter (Linux), postgres_exporter, redis_exporter...
PromQL cơ bản
| Biểu thức | Ý nghĩa |
|---|---|
http_request_duration_seconds_count{job="notes-api"} | Instant vector: giá trị mới nhất của mọi chuỗi khớp label |
...[5m] | Range vector: mọi mẫu trong 5 phút gần nhất |
rate(counter[5m]) | Tốc độ tăng trung bình mỗi giây trong 5 phút, tự xử lý counter bị reset |
increase(counter[1h]) | Tổng mức tăng trong 1 giờ (= rate × 3600) |
sum by (pod) (...) | Cộng các chuỗi, giữ lại label pod; sum without (instance) thì ngược lại |
histogram_quantile(0.95, sum by (le) (rate(..._bucket[5m]))) | Ước lượng p95 từ histogram |
Hai quy tắc vàng: luôn rate() trước rồi mới sum(), và chỉ dùng rate/increase cho counter, không cho gauge.
kube-prometheus-stack và Prometheus Operator
Tự cấu hình Prometheus cho Kubernetes khá vất vả. Helm chart kube-prometheus-stack gói sẵn mọi thứ:
| Thành phần | Vai trò |
|---|---|
| Prometheus Operator | Controller đọc các CRD bên dưới và sinh cấu hình cho Prometheus, Alertmanager |
| Prometheus | Chạy dưới dạng StatefulSet, scrape và lưu số liệu, đánh giá rule |
| Alertmanager | Nhận alert, gom nhóm, chống trùng, định tuyến tới Slack/email... |
| Grafana | Dashboard, kèm sẵn hàng chục dashboard cho Kubernetes |
| node-exporter | DaemonSet, metrics phần cứng và hệ điều hành của từng node |
| kube-state-metrics | Biến trạng thái đối tượng K8s thành metrics: replica, restart, phase, requests/limits |
| Rule mặc định | Hàng trăm recording rule và alert rule đã được cộng đồng tinh chỉnh |
Thay vì sửa file cấu hình Prometheus, bạn khai báo CRD (chương 14 giải thích CRD và Operator pattern kỹ hơn):
- ServiceMonitor: "hãy scrape các endpoint của những Service có label X, ở port tên Y".
- PodMonitor: giống vậy nhưng chọn thẳng Pod, dùng khi không có Service.
- PrometheusRule: các recording rule và alert rule.
IMPORTANT
Mặc định, Prometheus do chart tạo ra chỉ chọn ServiceMonitor, PodMonitor và PrometheusRule có label release: <tên release Helm>. Thiếu label này, đối tượng của bạn bị bỏ qua mà không báo lỗi gì. Đây là bẫy số một khi dùng kube-prometheus-stack.
Thực hành
Bước 1: cài kube-prometheus-stack
Stack này khá nặng: trên kind, dự trù thêm khoảng 2 GB RAM cho Docker. File values dưới đây giảm thời gian lưu trữ và tắt việc scrape các thành phần control plane mà kind chỉ mở ở 127.0.0.1 (nếu để bật, các target đó luôn down và alert tương ứng kêu liên tục):
prometheus:
prometheusSpec:
retention: 2d
resources:
requests:
cpu: 200m
memory: 512Mi
kubeEtcd:
enabled: false
kubeControllerManager:
enabled: false
kubeScheduler:
enabled: false
kubeProxy:
enabled: falsehelm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm search repo prometheus-community/kube-prometheus-stack
helm install monitoring prometheus-community/kube-prometheus-stack \
-n monitoring --create-namespace -f monitoring-values.yaml
kubectl get pods -n monitoringNAME READY STATUS RESTARTS AGE
alertmanager-monitoring-kube-prometheus-alertmanager-0 2/2 Running 0 2m
monitoring-grafana-6d9f8b7c5-x8k2p 3/3 Running 0 2m
monitoring-kube-prometheus-operator-7f6c9d8b4-lm2qz 1/1 Running 0 2m
monitoring-kube-state-metrics-5b8c7d9f6-p4n7w 1/1 Running 0 2m
monitoring-prometheus-node-exporter-4xk9z 1/1 Running 0 2m
monitoring-prometheus-node-exporter-9tq2m 1/1 Running 0 2m
monitoring-prometheus-node-exporter-hv7rc 1/1 Running 0 2m
prometheus-monitoring-kube-prometheus-prometheus-0 2/2 Running 0 2mNOTE
Bài không ghim phiên bản chart vì chart ra bản mới rất thường xuyên. Trong dự án thật, chạy helm search repo để xem bản hiện tại, đọc ghi chú nâng cấp, rồi ghim bằng --version (hoặc trong Argo CD, chương 12).
Mở giao diện Prometheus:
kubectl port-forward -n monitoring svc/monitoring-kube-prometheus-prometheus 9090:9090Vào http://localhost:9090, mục Status → Targets (Prometheus 3 gọi là Target health) liệt kê mọi target và trạng thái UP/DOWN. Thử truy vấn up ở tab Query: mỗi target là một chuỗi, giá trị 1 nghĩa là scrape thành công.
Bước 2: gắn đo lường cho notes-api với prom-client
Cài thư viện (npm install prom-client) rồi thêm vào server.js, trước khai báo các route:
const client = require("prom-client");
client.collectDefaultMetrics(); // CPU, heap, event loop lag... của tiến trình Node.js
const httpDuration = new client.Histogram({
name: "http_request_duration_seconds",
help: "Thời gian xử lý request HTTP",
labelNames: ["method", "route", "status_code"],
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5],
});
app.use((req, res, next) => {
const end = httpDuration.startTimer();
res.on("finish", () => {
// Dùng mẫu route (/notes) thay vì URL thật để số chuỗi không bùng nổ
end({ method: req.method, route: req.route ? req.route.path : "unmatched", status_code: res.statusCode });
});
next();
});
app.get("/metrics", async (req, res) => {
res.set("Content-Type", client.register.contentType);
res.end(await client.register.metrics());
});Một histogram duy nhất cho bạn cả ba con số của phương pháp RED (Rate, Errors, Duration): _count cho tốc độ request, _count lọc theo status_code cho tỉ lệ lỗi, _bucket cho phân vị độ trễ.
Build bản notes-api:1.2 (chỉ thêm /metrics) và triển khai:
docker build -t notes-api:1.2 .
kind load docker-image notes-api:1.2 --name hoc-k8s
kubectl set image deploy/notes-api -n notes notes-api=notes-api:1.2
kubectl rollout status deploy/notes-api -n notesNếu notes-api đang được quản lý bằng Helm chart từ chương 12, hãy đổi image.tag qua helm upgrade thay vì kubectl set image, và đưa các manifest ở bước 3, 5 vào thư mục templates/ của chart.
Bước 3: Service có port đặt tên và ServiceMonitor
ServiceMonitor tham chiếu port theo tên, và chọn Service theo label của chính Service (không phải label của Pod):
apiVersion: v1
kind: Service
metadata:
name: notes-api
namespace: notes
labels:
app: notes-api
spec:
selector:
app: notes-api
ports:
- name: http
port: 80
targetPort: 3000apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: notes-api
namespace: notes
labels:
release: monitoring
spec:
selector:
matchLabels:
app: notes-api
endpoints:
- port: http
path: /metrics
interval: 15skubectl apply -f notes-api-service.yaml -f notes-api-servicemonitor.yamlSau khoảng nửa phút, trang Targets có nhóm serviceMonitor/notes/notes-api/0 với 3 endpoint UP. Prometheus scrape từng Pod qua EndpointSlice (không đi qua ClusterIP), và gắn thêm label namespace, pod, service, job="notes-api" (mặc định lấy theo tên Service).
WARNING
Nếu namespace notes có NetworkPolicy mặc định chặn ingress (chương 11), Prometheus ở namespace monitoring sẽ không scrape được (target báo context deadline exceeded). Thêm một NetworkPolicy cho phép ingress từ namespace monitoring (chọn bằng label kubernetes.io/metadata.name: monitoring) tới cổng 3000 của Pod app: notes-api.
Tạo chút lưu lượng để có số liệu:
kubectl run load -n notes --rm -it --image=busybox:1.37 --restart=Never -- \
sh -c 'while true; do wget -qO- http://notes-api/notes >/dev/null; sleep 0.1; done'Bước 4: những truy vấn nên thuộc
RED cho notes-api (góc nhìn người dùng):
# Rate: số request mỗi giây
sum(rate(http_request_duration_seconds_count{job="notes-api"}[5m]))
# Errors: tỉ lệ request 5xx
sum(rate(http_request_duration_seconds_count{job="notes-api", status_code=~"5.."}[5m]))
/ sum(rate(http_request_duration_seconds_count{job="notes-api"}[5m]))
# Duration: p95 độ trễ theo route
histogram_quantile(0.95,
sum by (le, route) (rate(http_request_duration_seconds_bucket{job="notes-api"}[5m])))Container so với requests/limits (từ cAdvisor kết hợp kube-state-metrics):
# CPU đang dùng / CPU request (> 1 nghĩa là dùng vượt request)
sum by (pod) (rate(container_cpu_usage_seconds_total{namespace="notes", container="notes-api"}[5m]))
/ sum by (pod) (kube_pod_container_resource_requests{namespace="notes", container="notes-api", resource="cpu"})
# Tỉ lệ chu kỳ CPU bị throttle (trên 0.25 kéo dài là đáng lo)
sum by (pod) (rate(container_cpu_cfs_throttled_periods_total{namespace="notes"}[5m]))
/ sum by (pod) (rate(container_cpu_cfs_periods_total{namespace="notes"}[5m]))
# Memory working set / memory limit (gần 1 là sắp OOMKilled)
sum by (pod) (container_memory_working_set_bytes{namespace="notes", container="notes-api"})
/ sum by (pod) (kube_pod_container_resource_limits{namespace="notes", container="notes-api", resource="memory"})Sức khỏe workload (kube-state-metrics):
# Container khởi động lại trong 1 giờ qua
increase(kube_pod_container_status_restarts_total{namespace="notes"}[1h]) > 0
# Pod đang không Ready
sum by (namespace, pod) (kube_pod_status_ready{condition="false"}) > 0USE cho node (Utilization, Saturation, Errors), góc nhìn tài nguyên hạ tầng:
# Utilization: % CPU và % memory đang dùng
1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes
# Saturation: tiến trình phải chờ CPU (PSI) và tải trung bình
rate(node_pressure_cpu_waiting_seconds_total[5m])
node_load1
# Errors: lỗi card mạng
rate(node_network_receive_errs_total[5m])RED trả lời "người dùng có ổn không", USE trả lời "máy có ổn không". Bắt đầu điều tra từ RED, rồi mới đi xuống USE.
Bước 5: alert với PrometheusRule
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: notes-api-alerts
namespace: notes
labels:
release: monitoring
spec:
groups:
- name: notes-api
rules:
- alert: NotesApiCrashLooping
expr: increase(kube_pod_container_status_restarts_total{namespace="notes", container="notes-api"}[15m]) >= 3
for: 5m
labels:
severity: critical
annotations:
summary: "Pod {{ $labels.pod }} khởi động lại liên tục"
description: "{{ $value | humanize }} lần khởi động lại trong 15 phút qua."
- alert: NotesApiHighErrorRate
expr: |
sum(rate(http_request_duration_seconds_count{job="notes-api", status_code=~"5.."}[5m]))
/ sum(rate(http_request_duration_seconds_count{job="notes-api"}[5m])) > 0.05
for: 10m
labels:
severity: warning
annotations:
summary: "notes-api trả lỗi 5xx cho hơn 5% request"for: 10m nghĩa là điều kiện phải đúng liên tục 10 phút: alert đi từ inactive sang pending, rồi mới firing. Nhờ vậy một đợt lỗi ngắn không đánh thức ai. Kiểm tra ở trang Alerts của Prometheus.
Alertmanager nhận alert đang firing và quyết định gửi đi đâu:
- Gom nhóm (grouping): 30 Pod cùng lỗi thành một thông báo thay vì 30.
- Định tuyến (routing): cây route khớp theo label, ví dụ
severity="critical"gửi tới kênh trực. - Ức chế (inhibition): node chết thì không cần báo thêm từng Pod trên node đó.
- Tạm tắt (silence): tắt cảnh báo trong khung giờ bảo trì, đặt trên giao diện Alertmanager.
Cấu hình qua values của chart:
alertmanager:
config:
route:
receiver: "null"
group_by: ["alertname", "namespace"]
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
- matchers: ['severity="critical"']
receiver: slack-oncall
receivers:
- name: "null"
- name: slack-oncall
slack_configs:
- api_url: https://hooks.slack.com/services/T000/B000/XXXX
channel: "#oncall"
send_resolved: trueÁp dụng bằng helm upgrade monitoring prometheus-community/kube-prometheus-stack -n monitoring -f monitoring-values.yaml. Webhook Slack là bí mật: trong thực tế, đưa nó vào Secret thay vì commit vào Git (chương 7).
Bước 6: Grafana
kubectl get secret -n monitoring monitoring-grafana -o jsonpath='{.data.admin-password}' | base64 -d; echo
kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80Đăng nhập http://localhost:3000 với user admin và mật khẩu vừa lấy. Data source Prometheus đã được cấu hình sẵn. Vào Dashboards và mở:
- Kubernetes / Compute Resources / Namespace (Pods): chọn namespace
notes, xem CPU, memory của từng Pod so với requests/limits. - Kubernetes / Compute Resources / Pod: chi tiết một Pod, có cả biểu đồ CPU throttling.
- Node Exporter / Nodes: USE của từng node.
Dashboard cộng đồng nhập từ grafana.com bằng ID (Dashboards → New → Import, ví dụ 1860 là Node Exporter Full). Dashboard của riêng bạn nên lưu dưới dạng JSON trong một ConfigMap có label grafana_dashboard: "1": sidecar của Grafana trong chart tự nạp nó, nên dashboard được quản lý bằng Git như mọi manifest khác.
Log trong Grafana: Loki (giới thiệu)
Cài thêm Loki (kho log) và Grafana Alloy (agent DaemonSet, bài trước) bằng Helm chart của Grafana, thêm Loki làm data source, và bạn tra log ngay cạnh metrics bằng LogQL:
{namespace="notes", container="notes-api"} | json | status >= 500Tên label phụ thuộc cấu hình agent. Giá trị lớn nhất là liên kết: thấy tỉ lệ lỗi tăng trên dashboard, nhảy sang đúng khoảng thời gian đó trong log mà không cần kubectl logs từng Pod (vốn có thể đã bị xóa).
Ý tưởng SLO
Một SLO (Service Level Objective) là mục tiêu đo được, ví dụ "99,5% request tới notes-api thành công trong 30 ngày". Phần còn lại, 0,5%, là ngân sách lỗi (error budget): tương đương khoảng 3,6 giờ ngừng hoàn toàn mỗi 30 ngày. Thay vì cảnh báo theo ngưỡng cố định, người ta cảnh báo khi ngân sách bị đốt quá nhanh (burn rate). Các công cụ như Sloth hay Pyrra sinh sẵn PrometheusRule cho mô hình này từ một khai báo SLO ngắn.
Bẫy thường gặp
1. ServiceMonitor không xuất hiện trong Targets
- Nguyên nhân thường gặp, theo thứ tự: thiếu label
release: monitoring;selectorcủa ServiceMonitor khớp label Pod nhưng Service không có label đó;port: httpnhưng port của Service không có tên (hoặc tên khác). - Cách sửa: kiểm tra
kubectl get svc -n notes notes-api --show-labelsvà phầnportstrong-o yaml. Muốn Prometheus chọn mọi ServiceMonitor bất kể label, đặtprometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues: false(tương tựpodMonitor...,rule...).
2. Target DOWN với context deadline exceeded
- Nguyên nhân: NetworkPolicy chặn, ứng dụng chỉ nghe
127.0.0.1, hoặc saipath. - Cách sửa: thử từ trong cluster bằng
kubectl run -n monitoring curl --rm -it --image=busybox:1.37 --restart=Never -- wget -qO- http://<pod-ip>:3000/metrics.
3. Bùng nổ số chuỗi (cardinality explosion)
- Triệu chứng: Prometheus ăn hết RAM, bị OOMKilled.
- Nguyên nhân: label chứa giá trị không giới hạn: URL thô
/notes/8812, user id, request id. - Cách sửa: dùng mẫu route, giữ label ít và có tập giá trị nhỏ. Kiểm tra ở Status → TSDB Status.
4. sum rồi mới rate, hoặc rate trên gauge
rate(sum(...))sai vì khi một Pod khởi động lại, counter của nó về 0, tổng bị tụt vàratehiểu nhầm. Luônsum(rate(...)). Với gauge (memory), dùng trực tiếp hoặcavg_over_time,max_over_time.
5. Dấu ngoặc nhọn trong Helm chart
- Triệu chứng: đưa PrometheusRule vào
templates/của chart thìhelm installbáo lỗi template, vì Helm cố hiểu{{ $labels.pod }}. - Cách sửa: thoát bằng
{{ "{{" }} $labels.pod {{ "}}" }}.
6. Alert mặc định kêu ầm ĩ trên kind
- Các rule cho etcd, scheduler, controller-manager báo
Downvì kind chỉ mở metrics ở127.0.0.1. Tắt các thành phần đó trong values như bước 1. AlertWatchdogluôn firing là có chủ đích: nó chứng minh đường ống cảnh báo còn sống.
Tóm tắt
- Prometheus kéo
/metricscủa các target theo chu kỳ và lưu thành chuỗi thời gian định danh bởi tên metric + label; label có giá trị không giới hạn làm bùng nổ số chuỗi. - Bốn loại metric: counter, gauge, histogram, summary. PromQL cốt lõi:
rate,increase,sum by,histogram_quantile; luônratetrướcsum. - kube-prometheus-stack (Helm, repo
prometheus-community) gồm Prometheus Operator, Prometheus, Alertmanager, Grafana, node-exporter, kube-state-metrics và bộ rule mặc định. - Khai báo scrape bằng ServiceMonitor (chọn Service theo label, port theo tên) hoặc PodMonitor; alert bằng PrometheusRule. Nhớ label
release: <tên release>. - notes-api dùng
prom-client: default metrics + một histogramhttp_request_duration_secondsđủ cho RED (rate, errors, duration); node dùng USE (utilization, saturation, errors). - Các truy vấn nên thuộc: CPU so với request, tỉ lệ throttling, working set so với memory limit, số lần restart, Pod không Ready.
- Alertmanager gom nhóm, định tuyến, ức chế và tạm tắt cảnh báo;
for:tránh báo động vì sự cố thoáng qua. - Grafana có sẵn dashboard Kubernetes; lưu dashboard riêng trong ConfigMap có label
grafana_dashboard: "1". Loki đưa log vào cùng giao diện; SLO và error budget giúp cảnh báo theo trải nghiệm người dùng.
Comments