云计算百科
云计算领域专业知识百科平台

nginx ngx_http_stub_status_module配置详解:提供基本的服务器状态信息

ngx_http_stub_status_module 是 Nginx 的一个模块,用于提供基本的服务器状态信息。这个模块可以帮助你监控 Nginx 的运行状态,包括活动连接数、已处理请求数等。这些信息对于性能调优和故障排查非常有用。

配置详解

1. stub_status

启用状态页面,提供服务器的基本状态信息。

  • 语法:

    stub_status;

  • 上下文:

    • location
  • 示例:

    location /nginx_status {
    stub_status;
    allow 127.0.0.1; # 只允许本地访问
    deny all; # 拒绝其他所有访问
    }

状态信息说明

启用 stub_status 后,访问指定的 URI(例如 /nginx_status)会返回以下格式的状态信息:

Active connections: 3
server accepts handled requests
10 10 15
Reading: 1 Writing: 1 Waiting: 1

  • Active connections:当前活动的连接数。
  • server accepts handled requests:
    • accepts:Nginx 接收到的连接总数。
    • handled:已处理的连接总数(通常与 accepts 相同)。
    • requests:已处理的请求数。
  • Reading:当前处于读取客户端请求状态的连接数。
  • Writing:当前处于向客户端发送响应状态的连接数。
  • Waiting:当前处于等待状态的连接数(通常是保持连接的状态)。

使用场景

  • 监控服务器状态:

    • 通过访问状态页面,可以实时监控 Nginx 的运行状态,了解服务器的负载情况。
  • 集成监控工具:

    • 可以将状态页面集成到监控工具中,例如 Prometheus、Grafana 等,以便进行更详细的性能分析和告警。
  • 示例配置

    以下是一个完整的 Nginx 配置示例,展示了如何使用 ngx_http_stub_status_module 中的 stub_status 指令:

    user nginx;
    worker_processes auto;
    error_log /var/log/nginx/error.log;
    pid /run/nginx.pid;

    events {
    worker_connections 1024;
    }

    http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr – $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    client_max_body_size 10m;

    server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html index.htm;

    # 启用状态页面
    location /nginx_status {
    stub_status;
    allow 127.0.0.1; # 只允许本地访问
    deny all; # 拒绝其他所有访问
    }

    location / {
    # 其他配置
    }
    }
    }

    注意事项

  • 安全访问控制:

    • 使用 allow 和 deny 指令限制对状态页面的访问,确保只有授权的客户端可以访问。例如,只允许本地访问或特定 IP 地址访问。
  • 性能影响:

    • 启用状态页面对 Nginx 的性能影响很小,但在高负载情况下,频繁访问状态页面可能会增加一些额外的开销。
  • 日志记录:

    • 如果需要记录状态页面的访问日志,可以在 location 块中单独配置 access_log。
  • 示例:集成 Prometheus

    如果你想将 Nginx 的状态信息集成到 Prometheus 中,可以使用 nginx-prometheus-exporter 这样的工具。以下是一个简单的配置示例:

  • 安装 nginx-prometheus-exporter:

    docker run -d –name nginx-exporter \\
    -p 9113:9113 \\
    –link nginx \\
    nginx/nginx-prometheus-exporter:latest \\
    -nginx.scrape-uri http://nginx:80/nginx_status

  • 配置 Prometheus: 在 Prometheus 的配置文件 prometheus.yml 中添加一个 job 来抓取 Nginx 的指标:

    scrape_configs:
    job_name: 'nginx'
    static_configs:
    targets: ['localhost:9113']

  • 通过这种方式,你可以将 Nginx 的状态信息集成到 Prometheus 中,并使用 Grafana 等工具进行可视化展示。

    赞(0)
    未经允许不得转载:网硕互联帮助中心 » nginx ngx_http_stub_status_module配置详解:提供基本的服务器状态信息
    分享到: 更多 (0)

    评论 抢沙发

    评论前必须登录!