zabbix通过stub_status模块实现对nginx的监控

原理

nginx的ngx_http_stub_status_module模块提供了基本的nginx状态信息,源码安装的话需要加上–with-http_stub_status_module编译参数,或者如果是epel源yum安装的话,已经默认启用该模块。在nginx.conf的server段中添加:

location /basic_status {
    stub_status;
    access_log off;
}

那么访问http://xxx.com/basic_status就可以得到7个nginx运行信息了:

Active connections: 291 
server accepts handled requests
 16630948 16630948 31070465 
Reading: 6 Writing: 179 Waiting: 106

各项含义摘抄如下:

Active connections  The current number of active client connections including Waiting connections.

accepts  The total number of accepted client connections.

handled  The total number of handled connections. Generally, the parameter value is the same as acceptsunless some resource limits have been reached (for example, the worker_connections limit).

requests  The total number of client requests.

Reading  The current number of connections where nginx is reading the request header.

Writing  The current number of connections where nginx is writing the response back to the client.

Waiting  The current number of idle client connections waiting for a request.

Active connections/Reading/Writing/Waiting 是状态量,体现了nginx当前的运行状态,需要重点关注。

accepts/handled/requests是统计量,是个历史计数器,其中requests可以反映出“吞吐量”的概念,accepts和handled的差值可以反映出“丢包量”,即nginx由于某种原因丢弃的连接。

由此可以看出,zabbix监控nginx就是通过搜集以上数据,并稍作加工,形成图表供分析。

自定义脚本

zabbix可以通过自定义参数收集自定义信息,详见:https://www.zabbix.com/documentation/3.2/manual/config/items/userparameters

首先需要一个脚本,得到所需数据,然后通过zabbix-agent传给zabbix-server。有几点思路:

1、使用shell脚本即可,简单实用,跟操作系统紧密结合。

2、因为有很多监控项,如果写多个脚本会很乱,最好写成函数形式。

3、直接取accepts和handled的值没什么实际意义,它们的差值表示连接丢弃数量才是我们关心的。但是,这个计算不能放在zabbix-server中进行(item type — Calculation),因为zabbix在取两个值的时候有时间差,而这个时间差得到的结果会导致计算误差。所以必须在shell中算好,直接返回给zabbix-server。

ngx_status.sh代码如下:

#!/bin/bash


function active(){
/usr/bin/curl -s $URL |grep Active|awk '{print $3}'
}

function reading(){
/usr/bin/curl -s $URL |grep Reading|awk '{print $2}'
}

function writing(){
/usr/bin/curl -s $URL |grep Writing|awk '{print $4}'
}

function waiting(){
/usr/bin/curl -s $URL |grep Waiting|awk '{print $6}'
}

function requests(){
/usr/bin/curl -s $URL |awk '{if(NR==3) print $3}'
}

function dropped(){
/usr/bin/curl -s $URL > $FILE
accepts=`awk '{if(NR==3) print $1}' $FILE`
handled=`awk '{if(NR==3) print $2}' $FILE`
drop=`expr $accepts - $handled`
echo "$drop"
}

function ping(){
/usr/sbin/pidof nginx|wc -l
}

#根据脚本参数执行对应应函数
$1

zabbix-agent端添加以下配置:

# cat /etc/zabbix/zabbix_agentd.d/nginx_status.conf
UserParameter=nginx.status[*],/etc/zabbix/zabbix_agentd.d/nginx_status.sh $1

创建zabbix模版

active/reading/writing/waiting/requests都是一样的,方法如下:

吞吐量是由计算得出:

上面使用计算的方法没必要,官方已经提供了内置的delta数据类型来处理此类需求:

nginx存活状态是个布尔量,创建方法:

可以对这个item配置trigger,当nginx挂了做相应操作。

最后,我们可以创建几个图表,方便分析,因为是测试环境,基本没啥访问量^_^:

模版文件,适用于zabbix-3.2.7-1:https://github.com/dmli30/shell/blob/master/zabbix/ngx_status_templates.xml

标签:监控ZabbixNginx 发布于:2019-11-15 18:08:27