在Nginx中配置服务状态检测主要有以下几种方式,我会详细介绍每种方法的配置步骤:
这是Nginx自带的简单监控模块,可以查看基本连接信息。
配置方法:
server {
listen 80;
server_name status.example.com; # 建议使用专用域名
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1; # 只允许本地IP访问
allow 192.168.1.0/24; # 或允许内网IP段
deny all; # 拒绝其他所有IP
}
}
访问效果:
Active connections: 3
server accepts handled requests
100 100 100
Reading: 0 Writing: 1 Waiting: 2
Nginx Plus商业版支持主动健康检查,开源版可以通过以下方式实现被动检查:
upstream backend {
server 192.168.1.100:8080;
server 192.168.1.101:8080;
# 被动健康检查参数
max_fails=3 fail_timeout=30s;
}
server {
location / {
proxy_pass http://backend;
# 添加健康检查头
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 健康检查端点
location /health {
access_log off;
return 200 "OK";
add_header Content-Type text/plain;
}
}
需要编译安装:
./configure --with-http_stub_status_module --add-module=/path/to/ngx_http_status_module
make && make install
配置示例:
status_zone server http;
status server {
listen 8080;
allow 127.0.0.1;
deny all;
}
location /status {
access_log off;
content_by_lua_block {
local status = require "ngx.status"
ngx.say("Nginx worker PID: ", ngx.worker.pid())
ngx.say("Active connections: ", status.get_connections().active)
}
}
使用nginx-lua-prometheus模块:
lua_shared_dict prometheus_metrics 10M;
init_by_lua_block {
prometheus = require("prometheus").init("prometheus_metrics")
metric_requests = prometheus:counter(
"nginx_http_requests_total", "Number of HTTP requests", {"host", "status"})
metric_latency = prometheus:histogram(
"nginx_http_request_duration_seconds", "HTTP request latency", {"host"})
}
log_by_lua_block {
metric_requests:inc(1, {ngx.var.server_name, ngx.var.status})
metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name})
}
location /metrics {
content_by_lua_block {
prometheus:collect()
}
}
生产环境建议组合使用多种方式:
安全注意事项:
性能考虑:
Kubernetes环境:
livenessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 3
periodSeconds: 5
readinessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 3
periodSeconds: 5
根据您的具体需求选择合适的监控方案,简单的状态检查使用stub_status即可,如需更全面的监控建议采用Prometheus方案。