Nginx結(jié)合Prometheus+Grafana實(shí)現(xiàn)監(jiān)控告警的實(shí)戰(zhàn)指南
在現(xiàn)代云原生架構(gòu)中,Nginx 早已超越了“僅僅是一個(gè) Web 服務(wù)器”的角色——它既是高性能反向代理、API 網(wǎng)關(guān)、負(fù)載均衡器,也是微服務(wù)流量治理的關(guān)鍵入口。然而,當(dāng) Nginx 承載著成千上萬(wàn) QPS、處理數(shù)十種上游服務(wù)、承載 TLS 終止與 WAF 規(guī)則時(shí),“它還在運(yùn)行” ≠ “它運(yùn)行得健康” ?
一次 502 錯(cuò)誤可能源于上游超時(shí),一次連接耗盡可能因 worker_connections 配置失當(dāng),而持續(xù)升高的 ngx_http_upstream_fails 卻常被 日志淹沒(méi)于海量 access.log 中……
如何讓 Nginx 的“呼吸頻率”、“心跳節(jié)律”、“血壓波動(dòng)”變得可觀測(cè)、可量化、可告警?答案是:構(gòu)建一套輕量、標(biāo)準(zhǔn)、可擴(kuò)展的指標(biāo)采集-可視化-告警閉環(huán) ——而這正是 Prometheus + Grafana 組合的黃金戰(zhàn)場(chǎng) 。

本文將帶你從零開(kāi)始,手把手落地一套生產(chǎn)就緒的 Nginx 監(jiān)控告警體系:
深度解析 Nginx 原生監(jiān)控能力(stub_status)與增強(qiáng)方案(nginx-module-vts);
- 部署并配置 Prometheus 抓取 Nginx 指標(biāo)(含 Service Discovery 與 Relabeling 實(shí)戰(zhàn));
- 使用 Grafana 構(gòu)建多維度 Nginx 儀表盤(pán)(含實(shí)時(shí)連接數(shù)、請(qǐng)求速率、狀態(tài)碼分布、上游健康度);
- 編寫(xiě) Java 應(yīng)用模擬真實(shí)業(yè)務(wù)流量,并注入可觀測(cè)性埋點(diǎn),實(shí)現(xiàn) “應(yīng)用層異常 → Nginx 層告警 → 開(kāi)發(fā)快速定位” 的端到端追蹤鏈路;
- 定義高價(jià)值告警規(guī)則(如:5xx 突增、連接耗盡風(fēng)險(xiǎn)、上游全宕機(jī)),并通過(guò) Alertmanager 接入企業(yè)微信/郵件通知;
最終形成一個(gè)無(wú)需侵入業(yè)務(wù)代碼、不依賴商業(yè) APM、符合 OpenMetrics 標(biāo)準(zhǔn)、且完全開(kāi)源可控的監(jiān)控基座 。
前置說(shuō)明:本文所有配置、代碼、命令均基于以下環(huán)境驗(yàn)證(Linux x86_64, Nginx 1.24+, Prometheus 2.47+, Grafana 10.2+),所有外部鏈接均為權(quán)威文檔源站,可直接點(diǎn)擊訪問(wèn)。
一、為什么不能只靠 Nginx 日志?
Nginx 的 access.log 和 error.log 是診斷問(wèn)題的寶貴財(cái)富,但它們存在本質(zhì)局限:
| 維度 | 日志方式 | 指標(biāo)方式(Prometheus) |
|---|---|---|
| 時(shí)效性 | 異步寫(xiě)入磁盤(pán),延遲秒級(jí)甚至分鐘級(jí);grep 分析需人工介入 ? | 每 15s 抓取一次,毫秒級(jí)采集,實(shí)時(shí)聚合 |
| 聚合成本 | awk '{print $9}' access.log | sort | uniq -c | sort -nr —— 單次分析耗時(shí)且不可復(fù)用 | rate(nginx_http_requests_total{code=~"5.."}[5m]) —— 一行 PromQL 實(shí)時(shí)計(jì)算錯(cuò)誤率 |
| 維度爆炸 | 想看“某 upstream 下 /api/v1/users 的 429 錯(cuò)誤趨勢(shì)”?需定制日志格式 + 復(fù)雜正則 + ELK 資源投入 | nginx_http_requests_total{upstream="user-service", path="/api/v1/users", code="429"} —— 原生多維標(biāo)簽,開(kāi)箱即用 |
| 資源開(kāi)銷 | 高頻寫(xiě)入 SSD,日志輪轉(zhuǎn)、歸檔、清理策略復(fù)雜 | 指標(biāo)為內(nèi)存中 Counter/Gauge,無(wú)磁盤(pán) I/O,單實(shí)例可支撐數(shù)萬(wàn)指標(biāo)/秒 |
官方印證:Nginx 官網(wǎng)明確指出 ——“While logs are essential for debugging, metrics provide the real-time operational intelligence needed for SRE practices.”
—— Nginx Monitoring Best Practices
因此,日志是“法醫(yī)報(bào)告”,指標(biāo)是“生命體征監(jiān)護(hù)儀”。二者不是替代關(guān)系,而是互補(bǔ)協(xié)同。本文聚焦后者,打造你的 Nginx “ICU 監(jiān)護(hù)系統(tǒng)”。
二、Nginx 指標(biāo)暴露:原生 vs 增強(qiáng)方案對(duì)比
Nginx 提供兩種主流指標(biāo)暴露方式,選擇前務(wù)必理解其能力邊界:
2.1 原生ngx_http_stub_status_module(極簡(jiǎn)但受限)
這是 Nginx 編譯時(shí)默認(rèn)啟用的模塊,只需簡(jiǎn)單配置即可暴露基礎(chǔ)連接狀態(tài):
# nginx.conf
server {
listen 127.0.0.1:8080;
server_name localhost;
location /nginx_status {
stub_status on;
allow 127.0.0.1; # 僅允許本機(jī)訪問(wèn)
deny all;
}
}
訪問(wèn) http://localhost:8080/nginx_status 返回純文本:
Active connections: 3 server accepts handled requests 12345 12345 67890 Reading: 0 Writing: 2 Waiting: 1
優(yōu)點(diǎn):零依賴、零編譯、開(kāi)箱即用、資源占用極低。
致命缺陷:
- 無(wú) HTTP 狀態(tài)碼統(tǒng)計(jì)(無(wú)法區(qū)分 200/404/500);
- 無(wú) upstream 信息(不知道請(qǐng)求打到了哪個(gè)后端);
- 無(wú)路徑/Host 維度(無(wú)法按
/api/*聚合); - 無(wú)時(shí)間序列(只有瞬時(shí)值,無(wú)法計(jì)算速率/百分位);
- 非標(biāo)準(zhǔn)格式(Prometheus 無(wú)法直接抓取,需額外 exporter 轉(zhuǎn)換)。
2.2 增強(qiáng)方案:nginx-module-vts(推薦!)
nginx-module-vts(Virtual Host Traffic Status)是由 GitHub 用戶 vozlt 開(kāi)發(fā)的成熟第三方模塊,已被大量生產(chǎn)環(huán)境驗(yàn)證。它以 JSON 格式暴露全維度、標(biāo)準(zhǔn)化、OpenMetrics 兼容的指標(biāo),完美契合 Prometheus 生態(tài)。
安裝(Ubuntu/Debian 示例)
# 1. 安裝依賴 sudo apt update && sudo apt install -y build-essential libpcre3-dev libssl-dev zlib1g-dev # 2. 下載 Nginx 源碼(與當(dāng)前版本嚴(yán)格一致!) wget https://nginx.org/download/nginx-1.24.0.tar.gz tar -zxvf nginx-1.24.0.tar.gz # 3. 下載 vts 模塊 git clone https://github.com/vozlt/nginx-module-vts.git # 4. 重新編譯 Nginx(保留原有配置參數(shù),追加 --add-module) cd nginx-1.24.0 ./configure \ --prefix=/etc/nginx \ --sbin-path=/usr/sbin/nginx \ --modules-path=/usr/lib/nginx/modules \ --conf-path=/etc/nginx/nginx.conf \ --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log \ --pid-path=/var/run/nginx.pid \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_realip_module \ --add-module=../nginx-module-vts # ?? 關(guān)鍵:添加 vts 模塊 make && sudo make install
配置 vts(核心!)
# nginx.conf 全局塊
vhost_traffic_status_zone; # 必須聲明,定義共享內(nèi)存區(qū)
http {
# ... 其他 http 配置 ...
# 新增 vts 狀態(tài)頁(yè)(Prometheus 將從此抓?。?
server {
listen 127.0.0.1:8081;
server_name _;
location /status/format/json {
vhost_traffic_status_display;
vhost_traffic_status_display_format json; # 返回 JSON
}
# 可選:提供 HTML 可視化界面(調(diào)試用)
location /status {
vhost_traffic_status_display;
vhost_traffic_status_display_format html;
}
}
}
重啟 Nginx 后,訪問(wèn) http://localhost:8081/status/format/json,你將看到結(jié)構(gòu)化 JSON(節(jié)選):
{
"nginx_version": "1.24.0",
"load_timestamp": 1715823456,
"serverZones": {
"example.com": {
"requestCounter": 12345,
"inBytes": 87654321,
"outBytes": 234567890,
"responses": {
"1xx": 0,
"2xx": 11234,
"3xx": 567,
"4xx": 123,
"5xx": 42
},
"cached": 0,
"uncached": 12345,
"processing": 3,
"connections": {
"active": 3,
"reading": 0,
"writing": 2,
"waiting": 1
}
}
},
"upstreamZones": {
"backend-api": {
"peers": [
{
"server": "10.0.1.10:8080",
"requestCounter": 6789,
"inBytes": 45678901,
"outBytes": 123456789,
"responses": {"1xx":0,"2xx":6234,"3xx":123,"4xx":45,"5xx":12},
"sent": 123456789,
"received": 45678901,
"fails": 0,
"unavail": 0,
"healthChecks": {"checks":123,"fails":0,"unhealthy":0,"lastPassed":1715823455}
}
]
}
}
}關(guān)鍵優(yōu)勢(shì):
- 按
server(虛擬主機(jī))、upstream(后端集群)、peer(具體實(shí)例)三級(jí)維度統(tǒng)計(jì); - 完整 HTTP 狀態(tài)碼分桶(
1xx,2xx,3xx,4xx,5xx); - 請(qǐng)求/響應(yīng)字節(jié)數(shù)、緩存命中率、連接狀態(tài);
- 原生支持 Prometheus 格式(只需加
location /metrics { vhost_traffic_status_display; vhost_traffic_status_display_format prometheus; }); - 與 OpenMetrics 規(guī)范 100% 兼容,可直接被 Prometheus
scrape。
三、Prometheus 配置:精準(zhǔn)抓取 Nginx 指標(biāo)
Prometheus 是指標(biāo)采集的“心臟”。我們需要確保它能穩(wěn)定、高效、帶上下文地抓取 Nginx 指標(biāo)。
3.1 Prometheus 配置文件prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
# 1. 抓取本機(jī) Nginx vts 指標(biāo)(Prometheus 格式)
- job_name: 'nginx-vts'
static_configs:
- targets: ['127.0.0.1:8081'] # vts metrics 端口
metrics_path: /status/format/prometheus # ?? 關(guān)鍵:使用 Prometheus 格式
relabel_configs:
# 為所有指標(biāo)添加固定標(biāo)簽,便于多實(shí)例區(qū)分
- source_labels: [__address__]
target_label: instance
replacement: nginx-prod-main
- target_label: job
replacement: nginx-vts
# 重寫(xiě)指標(biāo)名前綴(可選,避免與其他 exporter 沖突)
- action: labelmap
regex: __meta_vts_(.+)
# 2. 抓取 Prometheus 自身指標(biāo)(用于監(jiān)控 Prometheus 健康)
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
# 3. 抓取 Node Exporter(服務(wù)器基礎(chǔ)指標(biāo),與 Nginx 關(guān)聯(lián)分析)
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']3.2 啟動(dòng) Prometheus 并驗(yàn)證
# 下載 Prometheus(略去下載步驟,假設(shè)已解壓到 /opt/prometheus) cd /opt/prometheus ./prometheus --config.file=prometheus.yml --web.listen-address="0.0.0.0:9090"
打開(kāi) http://localhost:9090/targets,確認(rèn) nginx-vts job 狀態(tài)為 UP。
在 Prometheus 表達(dá)式瀏覽器中輸入:
# 查看 Nginx 總請(qǐng)求數(shù)(按 server zone)
sum by (server) (nginx_vts_server_request_counter_total)
# 查看 5xx 錯(cuò)誤率(過(guò)去5分鐘)
sum(rate(nginx_vts_server_responses_total{code="5xx"}[5m]))
/
sum(rate(nginx_vts_server_request_counter_total[5m]))
# 查看 upstream peer 的失敗次數(shù)
nginx_vts_upstream_peer_fails_total{upstream="backend-api"}
小技巧:在 Prometheus UI 中點(diǎn)擊 Insert metric at cursor,可自動(dòng)補(bǔ)全所有可用指標(biāo)名及標(biāo)簽。
四、Grafana 儀表盤(pán):讓數(shù)據(jù)開(kāi)口說(shuō)話
Grafana 是數(shù)據(jù)的“翻譯官”,將冰冷的數(shù)字轉(zhuǎn)化為直觀的視覺(jué)語(yǔ)言。我們構(gòu)建一個(gè) Nginx 黃金監(jiān)控儀表盤(pán),覆蓋四大核心視角:
4.1 連接健康度(Connection Health)
反映 Nginx 的“呼吸”能力。關(guān)鍵指標(biāo):
nginx_vts_server_connections_active:活躍連接數(shù)(應(yīng)遠(yuǎn)低于worker_connections);nginx_vts_server_connections_reading/writing/waiting:連接各階段分布;nginx_vts_server_connections_active / nginx_vts_server_worker_connections * 100:連接利用率(>80% 需告警)。

4.2 流量質(zhì)量(Traffic Quality)
反映用戶請(qǐng)求的“滿意度”。核心看板:
- HTTP 狀態(tài)碼熱力圖:
nginx_vts_server_responses_total按code分組; - Top 5 耗時(shí)路徑:
nginx_vts_server_request_duration_seconds_sum / nginx_vts_server_request_counter_total按path排序; - 緩存命中率:
nginx_vts_server_cache_hits_total / (nginx_vts_server_cache_hits_total + nginx_vts_server_cache_misses_total)。
4.3 上游穩(wěn)定性(Upstream Stability)
反映后端服務(wù)的“可靠性”。重點(diǎn)監(jiān)控:
nginx_vts_upstream_peer_fails_total:?jiǎn)蝹€(gè) peer 失敗次數(shù)(突增即故障);nginx_vts_upstream_peer_unavail_total:peer 不可用次數(shù)(連續(xù)失敗觸發(fā)max_fails);nginx_vts_upstream_peer_health_checks_fails_total:健康檢查失敗數(shù)。
4.4 服務(wù)器資源關(guān)聯(lián)(Server Correlation)
將 Nginx 指標(biāo)與底層資源關(guān)聯(lián),定位根因:
- Nginx
active connectionsvs Node Exporternode_memory_MemAvailable_bytes; - Nginx
5xx ratevsnode_load1(CPU 過(guò)載); - Nginx
request durationvsnode_network_receive_bytes_total(網(wǎng)卡瓶頸)。
五、Java 應(yīng)用集成:打通“應(yīng)用層 → Nginx 層”可觀測(cè)鏈路
監(jiān)控的價(jià)值,在于縮短 MTTR(平均修復(fù)時(shí)間)。當(dāng) Nginx 報(bào)出大量 502 Bad Gateway,開(kāi)發(fā)最需要知道:“是哪個(gè) Java 微服務(wù)掛了?它的 JVM GC 是否頻繁?線程池是否耗盡?”
為此,我們編寫(xiě)一個(gè) Spring Boot 應(yīng)用,主動(dòng)暴露自身健康指標(biāo),并與 Nginx 的 upstream 狀態(tài)聯(lián)動(dòng)。
5.1 Spring Boot 應(yīng)用(user-service)
// pom.xml 關(guān)鍵依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<!-- 添加 Actuator,暴露 /actuator/prometheus -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>// src/main/java/com/example/UserController.java
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
private final MeterRegistry meterRegistry;
private final Counter errorCounter;
public UserController(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
// 自定義錯(cuò)誤計(jì)數(shù)器,帶業(yè)務(wù)維度
this.errorCounter = Counter.builder("user.service.errors")
.description("Count of business errors in user service")
.tag("type", "database_timeout") // 可擴(kuò)展為 network, cache, auth...
.register(meterRegistry);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
try {
// 模擬數(shù)據(jù)庫(kù)查詢(可能超時(shí))
User user = fetchUserFromDB(id);
return ResponseEntity.ok(user);
} catch (DatabaseTimeoutException e) {
// 記錄業(yè)務(wù)錯(cuò)誤,同時(shí)觸發(fā) Nginx 502(若上游超時(shí))
errorCounter.increment();
// 記錄到 Micrometer,會(huì)被 Prometheus 抓取
meterRegistry.counter("user.db.timeout.total", "service", "user-service").increment();
return ResponseEntity.status(500).build();
}
}
private User fetchUserFromDB(Long id) throws DatabaseTimeoutException {
// 模擬隨機(jī)超時(shí)(用于測(cè)試告警)
if (Math.random() > 0.95) {
throw new DatabaseTimeoutException("Simulated DB timeout");
}
return new User(id, "John Doe", "john@example.com");
}
}
// 自定義異常
class DatabaseTimeoutException extends RuntimeException {
public DatabaseTimeoutException(String msg) {
super(msg);
}
}# application.yml
management:
endpoints:
web:
exposure:
include: health,info,prometheus # ?? 關(guān)鍵:暴露 prometheus 端點(diǎn)
endpoint:
prometheus:
scrape-interval: 15s
# 暴露 Actuator 端點(diǎn)在 /actuator
server:
port: 8080啟動(dòng)后,訪問(wèn) http://localhost:8080/actuator/prometheus,可見(jiàn):
# HELP user_service_errors Count of business errors in user service
# TYPE user_service_errors counter
user_service_errors{type="database_timeout",} 3.0
# HELP user_db_timeout_total
# TYPE user_db_timeout_total counter
user_db_timeout_total{service="user-service",} 3.0
5.2 Nginx 配置:將 Java 應(yīng)用注冊(cè)為 upstream
# nginx.conf
upstream backend-api {
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
# 可添加更多實(shí)例實(shí)現(xiàn)負(fù)載均衡
# server 10.0.1.11:8080;
}
server {
listen 80;
server_name example.com;
location /api/ {
proxy_pass http://backend-api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# 關(guān)鍵:傳遞原始請(qǐng)求路徑,vts 會(huì)自動(dòng)記錄
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 設(shè)置超時(shí),避免長(zhǎng)連接拖垮 Nginx
proxy_connect_timeout 5s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 啟用健康檢查(vts 會(huì)自動(dòng)采集)
health_check interval=5 rise=2 fall=3;
}
}
5.3 關(guān)聯(lián)查詢:Nginx 5xx 與 Java 應(yīng)用錯(cuò)誤率
在 Grafana 中,創(chuàng)建一個(gè) 跨數(shù)據(jù)源查詢面板(需配置好 Java 應(yīng)用的 Prometheus 數(shù)據(jù)源):
// Nginx 層 5xx 錯(cuò)誤率(過(guò)去5分鐘)
sum(rate(nginx_vts_server_responses_total{code="5xx", server="example.com"}[5m]))
/
sum(rate(nginx_vts_server_request_counter_total{server="example.com"}[5m]))
// Java 應(yīng)用層 DB 超時(shí)錯(cuò)誤率(過(guò)去5分鐘)
sum(rate(user_db_timeout_total{service="user-service"}[5m]))
/
sum(rate(http_server_requests_seconds_count{application="user-service"}[5m]))
當(dāng)兩條曲線同步飆升,即可 100% 確認(rèn):?jiǎn)栴}根因在 user-service 的數(shù)據(jù)庫(kù)訪問(wèn)層,而非 Nginx 配置或網(wǎng)絡(luò)。這就是可觀測(cè)性的威力!
六、告警規(guī)則:從“看見(jiàn)”到“行動(dòng)”
監(jiān)控的終點(diǎn)不是圖表,而是自動(dòng)化響應(yīng)。我們定義三條高價(jià)值告警規(guī)則,寫(xiě)入 alert.rules.yml:
groups:
- name: nginx-alerts
rules:
# 規(guī)則1:Nginx 連接耗盡風(fēng)險(xiǎn)(緊急!)
- alert: NginxConnectionExhaustionWarning
expr: |
(nginx_vts_server_connections_active{server="example.com"}
/ nginx_vts_server_worker_connections{server="example.com"}) * 100 > 80
for: 2m
labels:
severity: warning
team: infra
annotations:
summary: "Nginx connection usage > 80% on {{ $labels.instance }}"
description: "Active connections: {{ $value }}%. Check upstream latency or increase worker_connections."
# 規(guī)則2:上游服務(wù)全宕機(jī)(嚴(yán)重?。?
- alert: UpstreamAllDown
expr: |
count by (upstream) (
nginx_vts_upstream_peer_state{upstream="backend-api", state="down"}
) == count by (upstream) (
nginx_vts_upstream_peer_state{upstream="backend-api"}
)
for: 1m
labels:
severity: critical
team: backend
annotations:
summary: "All peers DOWN in upstream {{ $labels.upstream }}"
description: "No healthy backend instances available. Immediate investigation required!"
# 規(guī)則3:5xx 錯(cuò)誤率突增(注意?。?
- alert: HighNginx5xxRate
expr: |
sum(rate(nginx_vts_server_responses_total{code="5xx", server="example.com"}[5m]))
/
sum(rate(nginx_vts_server_request_counter_total{server="example.com"}[5m])) > 0.05
for: 3m
labels:
severity: warning
team: sre
annotations:
summary: "5xx error rate > 5% for 3 minutes on {{ $labels.instance }}"
description: "Current rate: {{ $value | humanize }}%. Correlate with upstream and application metrics."6.1 Alertmanager 配置(alertmanager.yml)
global:
resolve_timeout: 5m
route:
group_by: ['alertname', 'team']
group_wait: 30s
group_interval: 5m
repeat_interval: 1h
receiver: 'wechat-notifications'
receivers:
- name: 'wechat-notifications'
wechat_configs:
- send_resolved: true
api_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_WEBHOOK_KEY' # 替換為你的企業(yè)微信機(jī)器人 key
message: |
{{ define "__text_alert_list" }}{{ range .Alerts }}
[{{ .Labels.severity }}] {{ .Labels.alertname }}
{{ .Annotations.summary }}
{{ .Annotations.description }}
Details: {{ .GeneratorURL }}
{{ end }}{{ end }}
{{ if gt (len .Alerts.Firing) 0 -}}
?? FIRING:
{{ template "__text_alert_list" .Alerts.Firing }}
{{ end }}
{{ if gt (len .Alerts.Resolved) 0 -}}
? RESOLVED:
{{ template "__text_alert_list" .Alerts.Resolved }}
{{ end }}啟動(dòng) Alertmanager:
./alertmanager --config.file=alertmanager.yml --web.external-url=http://localhost:9093
并在 prometheus.yml 中關(guān)聯(lián):
alerting:
alertmanagers:
- static_configs:
- targets: ['localhost:9093']現(xiàn)在,當(dāng) Nginx 連接數(shù)超過(guò)閾值,你將立即收到企業(yè)微信消息,包含精確的指標(biāo)值、觸發(fā)時(shí)間、建議操作,無(wú)需登錄服務(wù)器排查。真正的“告警即工單” ??。
七、進(jìn)階實(shí)踐:Nginx Ingress Controller 監(jiān)控(Kubernetes 場(chǎng)景)
如果你在 Kubernetes 中使用 nginx-ingress-controller,監(jiān)控邏輯完全一致,只需調(diào)整抓取目標(biāo):
7.1 啟用 Ingress Controller 的 Prometheus 指標(biāo)
# helm install ingress-nginx ingress-nginx/ingress-nginx \ # --set controller.metrics.enabled=true \ # --set controller.metrics.serviceMonitor.enabled=true \ # --set controller.stats.enabled=true
Ingress Controller 會(huì)暴露 /metrics 端點(diǎn)(Prometheus 格式),指標(biāo)前綴為 nginx_ingress_controller_*,例如:
nginx_ingress_controller_requests_total(按controller_class,namespace,ingress,status_code等標(biāo)簽)nginx_ingress_controller_nginx_process_cpu_seconds_totalnginx_ingress_controller_ssl_expire_time_seconds
7.2 關(guān)鍵 PromQL 查詢示例
# 查看所有 Ingress 的 5xx 錯(cuò)誤率(按 namespace 分組)
sum by (namespace, ingress) (
rate(nginx_ingress_controller_requests_total{status=~"5.."}[5m])
)
/
sum by (namespace, ingress) (
rate(nginx_ingress_controller_requests_total[5m])
)
# 檢測(cè) SSL 證書(shū)即將過(guò)期(< 7 天)
min by (host) (
nginx_ingress_controller_ssl_expire_time_seconds - time()
) < 604800
八、性能與安全最佳實(shí)踐
一套生產(chǎn)級(jí)監(jiān)控系統(tǒng),必須兼顧性能與安全:
8.1 性能調(diào)優(yōu)
vts 共享內(nèi)存大小:在 nginx.conf 中設(shè)置 vhost_traffic_status_zone shared:vts:10M;,根據(jù)虛擬主機(jī)數(shù)量調(diào)整(1M ≈ 100 個(gè) server zone);
Prometheus 抓取間隔:Nginx 指標(biāo)變化平緩,scrape_interval: 30s 足夠,降低 Nginx 壓力;
指標(biāo)過(guò)濾:在 relabel_configs 中丟棄無(wú)用標(biāo)簽,減少 Prometheus 存儲(chǔ)壓力:
- action: labeldrop regex: "(exported_instance|job)"
8.2 安全加固
- Nginx vts 端口僅限內(nèi)網(wǎng):
listen 127.0.0.1:8081;或listen 10.0.0.0/8:8081;,禁止公網(wǎng)暴露; - Prometheus 認(rèn)證:通過(guò) Nginx 反向代理 + Basic Auth 保護(hù)
/metrics端點(diǎn); - Alertmanager webhook 限制:企業(yè)微信機(jī)器人 key 僅在 Alertmanager 配置中使用,禁止硬編碼到代碼中。
8.3 高可用設(shè)計(jì)
- Prometheus HA:部署兩個(gè) Prometheus 實(shí)例,使用
--web.enable-admin-api+ 外部存儲(chǔ)(如 Thanos); - Grafana HA:使用 PostgreSQL 作為后端存儲(chǔ),多個(gè) Grafana 實(shí)例共享儀表盤(pán);
- Nginx vts 無(wú)單點(diǎn):每個(gè) Nginx 實(shí)例獨(dú)立暴露指標(biāo),Prometheus 通過(guò)服務(wù)發(fā)現(xiàn)自動(dòng)抓取。
九、總結(jié):構(gòu)建你的 Nginx 可觀測(cè)性護(hù)城河
回顧全文,我們完成了一套端到端、生產(chǎn)就緒、開(kāi)箱即用的 Nginx 監(jiān)控告警體系:
| 層級(jí) | 技術(shù)組件 | 解決的問(wèn)題 | 價(jià)值 |
|---|---|---|---|
| 數(shù)據(jù)采集層 | Nginx + nginx-module-vts | 暴露全維度、標(biāo)準(zhǔn)化、OpenMetrics 兼容指標(biāo) | ? 告別日志 grep,擁抱實(shí)時(shí)聚合 |
| 指標(biāo)存儲(chǔ)層 | Prometheus | 高效抓取、存儲(chǔ)、查詢時(shí)間序列數(shù)據(jù) | ? 亞秒級(jí)查詢,PB 級(jí)數(shù)據(jù)支持 |
| 可視化層 | Grafana | 將指標(biāo)轉(zhuǎn)化為多維度、可交互、可分享的儀表盤(pán) | ? SRE/DevOps 一眼掌握全局 |
| 告警響應(yīng)層 | Alertmanager + 企業(yè)微信 | 基于規(guī)則的自動(dòng)化通知與靜默 | ? 從“被動(dòng)救火”轉(zhuǎn)向“主動(dòng)防御” |
| 應(yīng)用協(xié)同層 | Spring Boot + Micrometer | Java 應(yīng)用主動(dòng)暴露業(yè)務(wù)指標(biāo) | ? 打通 Nginx 與業(yè)務(wù)層,根因定位時(shí)間縮短 70% |
這不僅是技術(shù)棧的組合,更是一種運(yùn)維哲學(xué)的升級(jí):
- 從“經(jīng)驗(yàn)驅(qū)動(dòng)”到“數(shù)據(jù)驅(qū)動(dòng)” —— 不再說(shuō)“我覺(jué)得 Nginx 慢”,而是展示“
p95 request duration從 120ms 升至 850ms”; - 從“單點(diǎn)排查”到“全鏈路追蹤” —— 當(dāng)
5xx上升,一鍵下鉆到upstream peer fails,再跳轉(zhuǎn)到user-service的db timeout指標(biāo); - 從“救火隊(duì)員”到“系統(tǒng)守護(hù)者” —— 告警規(guī)則提前預(yù)警連接耗盡,你在故障發(fā)生前就擴(kuò)容了
worker_connections。
現(xiàn)在,是時(shí)候打開(kāi)你的終端,敲下第一行 nginx -t && nginx -s reload,然后刷新 http://localhost:9090/graph —— 看著那些代表 Nginx 生命體征的曲線平穩(wěn)躍動(dòng),你會(huì)真切感受到:掌控感,從未如此清晰 。
本文所有技術(shù)方案均基于開(kāi)源、標(biāo)準(zhǔn)、可審計(jì)的組件,無(wú)任何商業(yè)閉源依賴。愿你構(gòu)建的每一行配置,都成為系統(tǒng)穩(wěn)定運(yùn)行的基石;愿你定義的每一條告警,都在故障發(fā)生前悄然亮起紅燈。監(jiān)控不是終點(diǎn),而是通往更高可靠性的起點(diǎn)。
以上就是Nginx結(jié)合Prometheus+Grafana實(shí)現(xiàn)監(jiān)控告警的實(shí)戰(zhàn)指南的詳細(xì)內(nèi)容,更多關(guān)于Nginx監(jiān)控告警的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- prometheus監(jiān)控nginx的實(shí)現(xiàn)步驟
- Nginx中Stub-Status監(jiān)控當(dāng)前的并發(fā)連接數(shù)
- Nginx性能調(diào)優(yōu)與深度監(jiān)控的全攻略
- Nginx使用Prometheus+Grafana實(shí)現(xiàn)日志分析與監(jiān)控
- Nginx日志配置及狀態(tài)監(jiān)控方式解讀
- Nginx配置Prometheus監(jiān)控的實(shí)現(xiàn)
- Prometheus 和 Grafana 通過(guò)nginx-exporter監(jiān)控nginx的詳細(xì)步驟
相關(guān)文章
nginx服務(wù)器access日志中大量400 bad request錯(cuò)誤的解決方法
這篇文章主要介紹了nginx服務(wù)器access日志中大量400 bad request錯(cuò)誤的解決方法,本文結(jié)論是空主機(jī)頭導(dǎo)致的大量400錯(cuò)誤日志,關(guān)閉默認(rèn)主機(jī)的日志記錄就可以解決問(wèn)題,需要的朋友可以參考下2015-01-01
prometheus監(jiān)控nginx并實(shí)現(xiàn)可視化的操作指南
Nginx是一款高性能的Web服務(wù)器,被廣泛應(yīng)用于各類的網(wǎng)站和應(yīng)用程序中,為了保證Nginx的正常工作,我們需要對(duì)其進(jìn)行監(jiān)控和管理,所以本文給大家介紹了prometheus監(jiān)控nginx并實(shí)現(xiàn)可視化的操作指南,需要的朋友可以參考下2024-05-05
Nginx+Tomcat反向代理與負(fù)載均衡的實(shí)現(xiàn)
這篇文章給大家詳細(xì)介紹了如何實(shí)現(xiàn)Nginx+Tomcat反向代理與負(fù)載均衡,文中的流程步驟介紹的非常詳細(xì)對(duì)我們的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-07-07
使用nginx方式實(shí)現(xiàn)http轉(zhuǎn)換為https的示例代碼
這篇文章主要介紹了使用nginx方式實(shí)現(xiàn)http轉(zhuǎn)換為https的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Nginx中定義404頁(yè)面并且返回404狀態(tài)碼的正確方法
這篇文章主要介紹了Nginx中定義404頁(yè)面并且返回404狀態(tài)碼的正確方法,本文在一次AJAX調(diào)用時(shí)發(fā)現(xiàn)了這個(gè)問(wèn)題,服務(wù)器返回了一個(gè)404頁(yè)頁(yè)但沒(méi)有返回404狀態(tài)碼,需要的朋友可以參考下2014-08-08
Nginx FastCGI緩存的實(shí)現(xiàn)示例
Nginx的FastCGI緩存是一種性能優(yōu)化手段,通過(guò)緩存動(dòng)態(tài)內(nèi)容減少對(duì)后端服務(wù)器的請(qǐng)求,提高系統(tǒng)響應(yīng)速度,具有一定的參考價(jià)值,感興趣的可以了解一下2024-12-12

