插件窝 干货文章 Nginx怎么配置检测服务状态

Nginx怎么配置检测服务状态

status Prometheus Nginx server 943    来源:    2025-04-21

在Nginx中配置服务状态检测主要有以下几种方式,我会详细介绍每种方法的配置步骤:

1. 使用Nginx内置的stub_status模块(基础监控)

这是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

2. 使用HTTP健康检查(推荐)

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;
    }
}

3. 第三方模块ngx_http_status_module

需要编译安装:

./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;
}

4. 使用Lua脚本扩展(OpenResty)

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)
    }
}

5. 结合Prometheus监控

使用nginx-lua-prometheus模块:

  1. 首先安装模块
  2. 配置nginx.conf:
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()
    }
}

最佳实践建议:

  1. 生产环境建议组合使用多种方式:

    • stub_status提供基础监控
    • Prometheus+Grafana实现可视化
    • 健康检查接口用于负载均衡
  2. 安全注意事项:

    • 所有状态接口必须限制访问IP
    • 建议使用HTTPS加密状态接口
    • 考虑添加HTTP Basic认证
  3. 性能考虑:

    • 状态检查接口应禁用access_log
    • 高流量环境下适当调整监控频率
  4. Kubernetes环境:

    livenessProbe:
     httpGet:
       path: /health
       port: 80
     initialDelaySeconds: 3
     periodSeconds: 5
    readinessProbe:
     httpGet:
       path: /health
       port: 80
     initialDelaySeconds: 3
     periodSeconds: 5
    

根据您的具体需求选择合适的监控方案,简单的状态检查使用stub_status即可,如需更全面的监控建议采用Prometheus方案。