【07】nginx:状态统计 / 状态码统计

写在前面的话

在 nginx 中,有些时候我们希望能够知道目前到底有多少个客户端连接到了我们的网站。我们希望有这样一个页面来专门统计显示这些情况。这个需求在 nginx 中是可以实现的,我们可以通过简单的配置来实现。

状态统计

nginx 自带模块中包含了 http_stub_status_module 模块,我们在之前的编译中也将其编译到了程序中,所以我们可以直接使用它:

在 vhosts 中新建:nginx-status.conf

server {
    listen      10002;
    server_name localhost;
    
    location = /status {
        stub_status on;
        access_log off;
    }

    location / {
        return 403;
    }
}

此时我们重载配置访问:

简单的说明:

Active connections:活跃的连接数量

server accepts handled requests:总共处理连接 / 成功握手次数 / 总共处理请求

Reading / Writing / Waiting:正在读取客户端连接数 / 响应数据到客户端的量 / 驻留连接 = Active - Reading - Writing

我们做个测试,在其它两台机器上面跑一个访问的循环:

while true; do curl http://192.168.100.111:10002 & sleep 1; done

让他一秒访问以下我们的 nginx,然后查看状态:

可以看到当前两个活跃连接,请求不断增加。

然后我们 stop nginx 后再启动查看:

发现之前的统计都被重置了,所以我们可以给出,这个统计是 nginx 启动之后的统计。当然 reload 不会。

状态码统计

处理统计多少人连接,处理了多少请求,我们也希望能够看懂每种请求状态码的出现的次数。

我们需要用到另外一个第三方模块:ngx_http_status_code_counter

https://github.com/kennon/ngx_http_status_code_counter

动态添加该模块的操作我们就不再做过多说明,因为前面已经介绍过很多次了。

编译替换完成以后,接下来就是配置,我们在原来 status 的配置上增加即可:nginx-status.conf

server {
    listen      10002;
    server_name localhost;
    
    location = /status {
        stub_status on;
        access_log off;
    }

    location = /status-codes {
        show_status_code_count on;
    }

    location / {
        return 403;
    }
}

此时我们访问测试:

值得注意的是,该统计在 nginx 重启或者 reload 以后都将重置为 0。

小结

本节的两个点都是用于帮助我们了解 nginx 使用状态的,你不能说它有多有用,但是确实能够帮到我们。

猜你喜欢

转载自www.cnblogs.com/Dy1an/p/11249412.html