ubuntu16.04更新web服务器apache为Nginx php-fpm

网站一直跑的是apache,觉得卡卡的。换nginx玩玩喽。nginx还是很强大的,感觉速度有些提升,奥力给!!!

已经安装了Apache2的话,要先删除再安装nginx!

删除Apache2

service apache2 stop
update-rc.d -f apache2 remove
apt-get remove apache2

安装nginx

apt-get -y install nginx

service nginx start

输入ip或域名就能看到 Welcome to Nginx!

安装 PHP 7

我们可以通过使nginx的PHP工作PHP-FPM(PHP-FPM(FastCGI进程管理器)是为任何规模的网站,尤其是繁忙的网站有用的一些附加功能的替代PHP的FastCGI实现),我们安装如下:

apt-get -y install php7.0-fpm

配置 nginx

虚拟主机服务器{}容器定义。默认的虚拟主机是在文件中定义的/etc/nginx/sites-available/default

将index index.html index.htm index.nginx-debian.html;

改成index index.html index.htm index.php;

server_name _;这里改成你的主机名,一般是域名。例如:server_name zerlong.com;

找到下边这一段,把注释去掉

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ .php$ {
                include snippets/fastcgi-php.conf;

                # With php7.0-cgi alone:
                #fastcgi_pass 127.0.0.1:9000;
                # With php7.0-fpm:
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }

注意上边fastcgi_pass只能用一个,不然会出错类似”fastcgi_pass”

directive is duplicate in /etc/nginx/sites-enabled/default

保存完重新加载nginx:

service nginx reload

编辑/etc/php/7.0/fpm/php.ini 设置 cgi.fix_pathinfo=0

service php7.0-fpm reload

建立个探针文件访问一下能出信息了,

未分类

MySQL 获得 PHP 7支持

使用下面的命令安装:

apt-get -y install php7.0-mysql php7.0-curl php7.0-gd php7.0-intl php-pear php-imagick php7.0-imap php7.0-mcrypt php-memcache  php7.0-pspell php7.0-recode php7.0-sqlite3 php7.0-tidy php7.0-xmlrpc php7.0-xsl php7.0-mbstring php-gettext

APCu是随PHP7 PHP Opcache模块的扩展,它增加了一些兼容性功能的支持APC缓存(例如WordPress的插件缓存)软件。

APCu可以安装如下:

apt-get -y install php-apcu

重新加载 PHP-FPM:

service php7.0-fpm reload

好了,跑起来吧网站!

附送nginx+https SSL配置

同时启用HTTP和HTTPS

server {
    listen              80;
    listen              443 ssl;
    server_name         zerlong.com;    #最好写绝对路径,你懂的
    ssl_certificate     zerlong.com.crt;
    ssl_certificate_key zerlong.com.key;
    ...

自动跳转https

server {
        listen   80;
        server_name zerlong.com;
        rewrite ^ https://$http_host$request_uri? permanent;    # force redirect http to https
        #return 301 https://$http_host$request_uri;
    }

server {
        listen 443 ssl;

        ssl_certificate /etc/nginx/ssl/nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/nginx.key;

        server_name zerlong.com;
        #禁止在header中出现服务器版本,防止黑客利用版本漏洞攻击
        server_tokens off;
        #如果是全站 HTTPS 并且不考虑 HTTP 的话,可以加入 HSTS 告诉你的浏览器本网站全站加密,并且强制用HTTPS 访问
        #add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
        # ......
        fastcgi_param   HTTPS              on;
        fastcgi_param   HTTP_SCHEME      https;

    }

wordpress的nginx伪静态规则

在站点配置文件的server { } 大括号里面添加下面的代码,然后重启nginx

location / {
if (-f $request_filename/index.html){
                rewrite (.*) $1/index.html break;
        }
if (-f $request_filename/index.php){
                rewrite (.*) $1/index.php;
        }
if (!-f $request_filename){
                rewrite (.*) /index.php;
        }
}

php-fpm占用内存过高分析及解决

昨天刚买了个vps搭建了一个wordPress博客,刚搭建的时候有一大堆的问题。好不容易搭建完成了发现运行一阵子以后内存几乎用完了。开始以为是服务器的问题,费了好大的劲把Apache服务器换成了Nginx。但是问题还是没有解决,最后用top命令看了一下是php-fpm的问题。问题的解决办法如下:

未分类

1、查看php-fpm的进程个数

ps -fe |grep "php-fpm"|grep "pool"|wc -l

2、查看每个php-fpm占用的内存大小

ps -ylC php-fpm --sort:rss

3、配置php-fpm参数

找到php-fpm的配置文件php-fpm.conf

pm = dynamic #对于专用服务器,pm可以设置为static。#如何控制子进程,选项有static和dynamic。如果选择static,则由pm.max_children指定固定的子进程数。如果选择dynamic,则由下开参数决定:
pm.max_children #子进程最大数
pm.start_servers #启动时的进程数
pm.min_spare_servers #保证空闲进程数最小值,如果空闲进程小于此值,则创建新的子进程
pm.max_spare_servers #保证空闲进程数最大值,如果空闲进程大于此值,此进行清理

对于内存大的服务器(比如8G以上)来说,指定静态的max_children实际上更为妥当,因为这样不需要进行额外的进程数目控制,会提高效率。

对于内存小的服务器,使用动态方式。具体最大数量根据 内存/20M 得到。比如512M的VPS,建议pm.max_spare_servers设置为20。至于pm.min_spare_servers,则建议根据服务器的负载情况来设置,比较合适的值在5~10之间。

解决Nginx php-fpm配置有误引起的502错误

在Ubuntu+Nginx+PHP环境下部署好以后,访问网站报错502,在后台nginx error_log里看到以下报错信息

2017/07/29 10:59:15 [error] 5622#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 183.14.134.39, server: xx.xx.xx.xx, request: “GET /index.php HTTP/1.1”, upstream: “fastcgi://127.0.0.1:9001”, host: “xx.xx.xx.xx”

通常这个报错是表示php-fpm这个服务未启动,由于默认是配置的9000端口,执行netstat -anp|grep 9000确实没有看到相关进程。

但执行命令查询php-fpm是running状态

# /etc/init.d/php7.0-fpm status
● php7.0-fpm.service – The PHP 7.0 FastCGI Process Manager
Loaded: loaded (/lib/systemd/system/php7.0-fpm.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2017-07-29 11:52:47 CST; 3h 43min ago
Process: 7191 ExecStartPre=/usr/lib/php/php7.0-fpm-checkconf (code=exited, status=0/SUCCESS)
Main PID: 7200 (php-fpm7.0)
Status: “Processes active: 0, idle: 2, Requests: 54, slow: 0, Traffic: 0req/sec”
CGroup: /system.slice/php7.0-fpm.service
├─7200 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf)
├─7203 php-fpm: pool www
└─7204 php-fpm: pool www

Jul 29 11:52:47 iZwz96f0gkw4blayus6g2yZ systemd[1]: Starting The PHP 7.0 FastCGI Process Manager…
Jul 29 11:52:47 iZwz96f0gkw4blayus6g2yZ systemd[1]: Started The PHP 7.0 FastCGI Process Manager.

查看/etc/php/7.0/fpm/pool.d/www.conf和/etc/php/7.0/fpm/php-fpm.conf发现以下参数:

listen = /run/php/php7.0-fpm.sock

查阅资料后才知道,原来php-fpm支持网络端口监听和socket两种方式,但后者效率更高。

针对该问题的解决方案是,修改nginx/conf/vhosts下的conf文件,

将fastcgi_pass 127.0.0.1:9000;修改为fastcgi_pass unix:/run/php/php7.0-fpm.sock;

重启Nginx服务后,WEB访问依然报错502,继续定位分析。

在nginx error_log日志中出现了以下新的报错内容:

2017/07/29 11:24:47 [crit] 6114#0: *1 connect() to unix:/run/php/php7.0-fpm.sock failed (13: Permission denied) while connecting to upstream, client: 183.14.134.xx, server: 112.74.89.xx, request: “GET / HTTP/1.1”, upstream: “fastcgi://unix:/run/php/php7.0-fpm.sock:”, host: “112.74.89.xx”

然后找到/etc/php/7.0/fpm/pool.d/www.conf文件,做以下处理:

注释掉

;listen.owner = www-data
;listen.group = www-data

将mode值修改为0666

listen.mode = 0666

最后,执行/etc/init.d/php7.0-fpm restart重启php-fpm服务,执行/etc/init.d/nginx restart重启Nginx服务,问题解决!!!

centos7系统下配置nginx php-fpm负载均衡

三台Centos7服务器

主:192.168.199.174
从:192.168.199.170
从:192.168.199.191

均全新最小化安装,都关闭了防火墙和SELINUX

第一步

先在 主服务器 上安装Nginx,可以在改配置前直接开启服务访问看看有没有问题,然后利用Nginx做请求转发

yum -y install nginx
systemctl start nginx.service
vi /etc/nginx/conf.d/default.conf

default.conf 修改后,删掉了注释部分

upstream myServer{
    server 192.168.199.170:9000 max_fails=3 fail_timeout=10s;
    server 192.168.199.191:9000 max_fails=3 fail_timeout=10s;
}
server {
    listen       80;
    server_name  localhost;
    location / {
        root   /home/wwwroot;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    location ~ .php$ {
        root           /home/wwwroot;
        fastcgi_pass   myServer;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

重新启动 Nginx 服务,顺便实时查看 Nginx 的日志,以便了解访问情况

systemctl restart nginx.service
tail -f /var/log/nginx/error.log /var/log/nginx/access.log

第二步

在 从服务器 上安装PHP

# 安装一些需要的东西
yum -y install wget libxml2-devel libtool
# 下载PHP
wget -O php-7.1.7.tar.gz http://php.net/get/php-7.1.7.tar.gz/from/this/mirror
# 复制一份到另一个从服务器,输入yes和191的密码
scp php-7.1.7.tar.gz [email protected]:/usr/local
# 将PHP安装包放到/usr/local目录
mv php-7.1.7.tar.gz /usr/local


# 从这里起,两台从服务器执行操作都一样
# 另一台服务器记得先执行上面yum 的那一行
# 进入/usr/local 目录
cd /usr/local
# 解压PHP安装包
tar -xvf php-7.1.7.tar.gz
# 进入PHP安装文件夹目录
cd php-7.1.7
# 安装PHP
./configure --enable-fpm
make && make install
# 复制和重命名配置文件
cp php.ini-development ../php/php.ini
cp ../etc/php-fpm.conf.default ../etc/php-fpm.conf
mv ../etc/php-fpm.d/www.conf.default ../etc/php-fpm.d/www.conf
# 创建fpm的软链接放入bin目录下,方便随处可用
ln -s sapi/fpm/php-fpm ../bin/php-fpm

修改 /usr/local/etc/php-fpm.conf 配置文件,在最后一行

include=/usr/local/etc/php-fpm.d/*.conf

修改 /usr/local/etc/php-fpm.d/www.conf 配置文件

listen = 0.0.0.0:9000
request_terminate_timeout = 0

以上操作在两台从服务器操作好后,分别启动PHP-FPM

php-fpm

第三步

开始测试

首先分别在两台从服务器上创建测试文件

cd /home
mkdir wwwroot
cd wwwroot
vi 1.php
<?php
// 这里的170换成当前从服务器的IP
// 比如191那台,这里就写191
echo("170");

浏览器打开:http://192.168.199.174/1.php

  • 第一次打开:170

  • 第一次刷新:191

  • 第二次刷新:170

  • 第三次刷新:191

与此同时,主服务器那边 nginx 的 error.log 没有变化,而 access.log 文件一直在记录各种成功的请求。

第四步:

配合 Laravel 的优雅链接设置

先修改 主服务器 的 /etc/nginx/conf.d/default.conf

# 就改了这一个 location 里的东西
location / {
    root   /home/wwwroot;
    index  index.html index.htm;
    # 就加了下面一段
    try_files $uri $uri/ /index.php?$query_string;
}

然后在 从服务器 的 /home/wwwroot 目录下建立 index.php 文件

<?php
echo '填170或191 <br />';
var_dump($_REQUEST);
echo '<hr />';
var_dump($_SERVER);

然后OK了,自己去测试吧。

Centos7安装配置mariaDB + nginx + php-fpm环境

Centos7 搭建mariaDB + nginx + php环境

系统更新

  • 1.安装开启安装EPEL YUM源
[root@localhost ~]# yum -y install epel-release
[root@localhost ~]# yum makecache
  • 2.系统更新
[root@localhost ~]# yum update
  • 3.解决The remote SSH server rejected X11 forwarding request提示
[root@localhost ~]# yum install xorg-x11-xauth
# 编辑/etc/ssh/sshd_config文件中的X11Forwarding参数为yes
[root@localhost ~]# vim /etc/ssh/sshd_config
  • 4.安装编译组件和依赖
[root@localhost ~]# yum -y install gcc gcc-c++ make unixODBC wxBase wxGTK wxGTK-gl ncurses-devel zlib zlib-devel openssl openssl-devel kernel-devel m4 xmlto net-tools lksctp-tools socat cmake perl perl-JSON libtool pcre pcre-devel yasm yasm-devel libmcrypt libmcrypt-devel libvpx libvpx-devel tiff tiff-devel libpng libpng-devel freetype freetype-devel jpeg jpeg-devel libgd libgd-devel t1lib t1lib-devel gd gd-devel

修改主机名

  • 1.将/etc/hostname中的值修改为localhost或者其他主机名
[root@localhost ~]# vim /etc/hostname
  • 2.在/etc/sysconfig/network 中添加或者修改为HOSTNAME=localhost或者其他主机名
[root@localhost ~]# vim /etc/sysconfig/network
  • 3.将/etc/hosts 中各项值修改为localhost或者其他主机名
[root@localhost ~]# vim /etc/hosts
  • 4.临时修改主机名
[root@localhost ~]# hostname localhost

添加用户

添加新的用户账号使用useradd命令,其语法如下

useradd 选项 用户名

其中各选项含义如下:
代码:

  • -c comment 指定一段注释性描述。
  • -d 目录 指定用户主目录,如果此目录不存在,则同时使用-m选项,可以创建主目录。
  • -g 用户组 指定用户所属的用户组。
  • -G 用户组,用户组 指定用户所属的附加组。
  • -s Shell文件 指定用户的登录Shell。
  • -u 用户号 指定用户的用户号,如果同时有-o选项,则可以重复使用其他用户的标识号。
  • 用户名 指定新账号的登录名

  • 1.添加nginx用户

[root@localhost ~]# groupadd nginx
[root@localhost ~]# useradd -c nginx -g nginx nginx -s /sbin/nologin
  • 2.添加网站专用wwwroot用户
[root@localhost ~]# groupadd www
[root@localhost ~]# useradd -c www -g www www -s /sbin/nologin

安装MARIADB

  • 1.使用yum命令安装mariaDB
[root@localhost]# yum -y install mariadb mariadb-server
  • 2.设置开机启动
[root@localhost ~]# systemctl enable mariadb
  • 3.启动MySQL服务
[root@localhost ~]# systemctl start mariadb
  • 4.MariaDB的相关简单配置
[root@localhost ~]# mysql_secure_installation
# 首先是设置密码,会提示先输入密码,初次运行直接回车
Enter current password for root (enter for none):
# 设置密码,是否设置root用户密码,输入y并回车或直接回车
Set root password? [Y/n]
# 设置root用户的密码
New password:
# 再输入一次你设置的密码
Re-enter new password:
# 其他配置
# 是否删除匿名用户,回车
Remove anonymous users? [Y/n]
# 是否禁止root远程登录,回车
Disallow root login remotely? [Y/n]
# 是否删除test数据库,回车
Remove test database and access to it? [Y/n]
# 是否重新加载权限表,回车
Reload privilege tables now? [Y/n]
# 初始化MariaDB完成,接下来测试登录
# mysql -uroot -proot密码
  • 5.授权远程用户登录
# 允许的IP地址,%为任意地址
mysql&gt; GRANT ALL PRIVILEGES ON *.* TO 'root'@'IP地址' IDENTIFIED BY 'youpassword' WITH GRANT OPTION;
mysql&gt; FLUSH PRIVILEGES;

安装PHP

  • 1.安装php
[root@localhost ~]# yum -y install php php-devel
  • 2.安装php扩展
[root@localhost ~]# yum -y install php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc
  • 3.安装php-fpm
# 安装 php-fpm
[root@localhost ~]# yum -y install php-fpm
# 设置fpm开机自启动
[root@localhost ~]# systemctl enable php-fpm
# 启动fpm
[root@localhost ~]# systemctl start php-fpm
# php-fpm配置文件路径/etc/php-fpm.conf

安装NGINX

  • 1.下载nginx
# 切换到src目录
[root@localhost ~]# cd /usr/local/src
# 下载nginx源码包
[root@localhost src]# wget http://nginx.org/download/nginx-1.12.0.tar.gz
# 解压并切换到nginx目录
[root@localhost src]# tar zxvf nginx-1.12.0.tar.gz
[root@localhost src]# cd nginx-1.12.0
# 配置编译选项
[root@localhost nginx-1.12.0]# ./configure --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-pcre
# 安装
[root@localhost nginx-1.12.0]# make &amp; make install
  • 2.启动关闭nginx
# 常规启动、关闭和重启,不会改变启动时指定的配置文件
[root@localhost ~]# /usr/local/nginx/sbin/nginx
[root@localhost ~]# /usr/local/nginx/sbin/nginx -s stop
[root@localhost ~]# /usr/local/nginx/sbin/nginx -s reload
# 设置开机自启动
[root@localhost ~]# vim /lib/systemd/system/nginx.service
# 写入以下内容
# --------------------------------------------------
[Unit]
Description=nginx
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
# --------------------------------------------------
[root@localhost ~]# systemctl enable nginx
  • 3.添加php支持
# 修改nginx.conf,去掉以下代码的注释
        location ~ .php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi_params;
        }
# 重启nginx
[root@localhost]# /usr/local/nginx/sbin/nginx -s reload
  • 4.解决访问php提示File not found.
# 修改nginx配置文件
# 源文件
fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
# 修改后的文件,将 /scripts 修改为$document_root
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;

zabbix监控php-fpm状态

本文通过启用php-fpm的status页面,使用zabbix来定时获取此数据以达到监控php-fpm性能状态的目的。

安装

假设zabbix agent安装在了/zabbix-agent/目录

配置php-fpm

打开php-fpm的pool配置文件,删除pm.status=指令的注释:

pm.status_path = /php-fpm_status

如果你配置了多个pool,需要分别为它们配置不同的status_path。

配置nginx

把如下配置添加到nginx配置文件:

server {
    listen 10061;

    location /php-fpm_status {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

重启php-fpm和nginx后,尝试执行如下命令测试:

curl http://127.0.0.1:10061/php-fpm_status

添加User Parameters

创建/zabbix-agent/etc/zabbix_agentd.conf.d/php-fpm-params.conf文件,内容如下:

UserParameter=php-fpm[*],/usr/local/zabbix-agent-ops/bin/php-fpm-check.sh "$1" "$2"

创建/usr/local/zabbix-agent-ops/bin/php-fpm-check.sh,内容如下:

#!/bin/bash
##################################
# Zabbix monitoring script
#
# php-fpm:
#  - anything available via FPM status page
#
##################################
# Contact:
#  [email protected]
##################################
# ChangeLog:
#  20100922 VV  initial creation
##################################

# Zabbix requested parameter
ZBX_REQ_DATA="$1"
ZBX_REQ_DATA_URL="$2"

# Nginx defaults
NGINX_STATUS_DEFAULT_URL="http://localhost:80/php-fpm_status"
WGET_BIN="/usr/bin/wget"

#
# Error handling:
#  - need to be displayable in Zabbix (avoid NOT_SUPPORTED)
#  - items need to be of type "float" (allow negative + float)
#
ERROR_NO_ACCESS_FILE="-0.9900"
ERROR_NO_ACCESS="-0.9901"
ERROR_WRONG_PARAM="-0.9902"
ERROR_DATA="-0.9903" # either can not connect / bad host / bad port

# Handle host and port if non-default
if [ ! -z "$ZBX_REQ_DATA_URL" ]; then
  URL="$ZBX_REQ_DATA_URL"
else
  URL="$NGINX_STATUS_DEFAULT_URL"
fi

# save the nginx stats in a variable for future parsing
NGINX_STATS=$($WGET_BIN -q $URL -O - 2> /dev/null)

# error during retrieve
if [ $? -ne 0 -o -z "$NGINX_STATS" ]; then
  echo $ERROR_DATA
  exit 1
fi

# 
# Extract data from nginx stats
#
RESULT=$(echo "$NGINX_STATS" | awk 'match($0, "^'"$ZBX_REQ_DATA"':[[:space:]]+(.*)", a) { print a[1] }')
if [ $? -ne 0 -o -z "$RESULT" ]; then
    echo $ERROR_WRONG_PARAM
    exit 1
fi

echo $RESULT

exit 0

导入模板

导入php-fpm-template.xml模板,并链接到主机。根据需要设置{$PHP_FPM_STATUS_URL}宏。
php-fpm-template.xml模板内容:

<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
    <version>2.0</version>
    <date>2013-03-26T04:12:09Z</date>
    <groups>
        <group>
            <name>Templates</name>
        </group>
    </groups>
    <templates>
        <template>
            <template>Template php-fpm</template>
            <name>Template php-fpm</name>
            <groups>
                <group>
                    <name>Templates</name>
                </group>
            </groups>
            <applications>
                <application>
                    <name>php-fpm</name>
                </application>
            </applications>
            <items>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["total processes",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["listen queue",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["listen queue len",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["active processes",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["idle processes",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1/sec</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["accepted conn",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>1</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1/sec</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["slow requests",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>1</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
            </items>
            <discovery_rules/>
            <macros>
                <macro>
                    <macro>{$PHP_FPM_STATUS_URL}</macro>
                    <value>http://127.0.0.1:10061/php-fpm_status</value>
                </macro>
            </macros>
            <templates/>
            <screens/>
        </template>
    </templates>
    <graphs>
        <graph>
            <name>php-fpm Accepted Connections / sec</name>
            <width>900</width>
            <height>200</height>
            <yaxismin>0.0000</yaxismin>
            <yaxismax>100.0000</yaxismax>
            <show_work_period>1</show_work_period>
            <show_triggers>1</show_triggers>
            <type>0</type>
            <show_legend>1</show_legend>
            <show_3d>0</show_3d>
            <percent_left>0.0000</percent_left>
            <percent_right>0.0000</percent_right>
            <ymin_type_1>0</ymin_type_1>
            <ymax_type_1>0</ymax_type_1>
            <ymin_item_1>0</ymin_item_1>
            <ymax_item_1>0</ymax_item_1>
            <graph_items>
                <graph_item>
                    <sortorder>0</sortorder>
                    <drawtype>0</drawtype>
                    <color>C80000</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["accepted conn",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
            </graph_items>
        </graph>
        <graph>
            <name>php-fpm Listen Queue</name>
            <width>900</width>
            <height>200</height>
            <yaxismin>0.0000</yaxismin>
            <yaxismax>100.0000</yaxismax>
            <show_work_period>1</show_work_period>
            <show_triggers>1</show_triggers>
            <type>0</type>
            <show_legend>1</show_legend>
            <show_3d>0</show_3d>
            <percent_left>0.0000</percent_left>
            <percent_right>0.0000</percent_right>
            <ymin_type_1>0</ymin_type_1>
            <ymax_type_1>0</ymax_type_1>
            <ymin_item_1>0</ymin_item_1>
            <ymax_item_1>0</ymax_item_1>
            <graph_items>
                <graph_item>
                    <sortorder>0</sortorder>
                    <drawtype>0</drawtype>
                    <color>EE0000</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["listen queue len",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
                <graph_item>
                    <sortorder>1</sortorder>
                    <drawtype>0</drawtype>
                    <color>00EE00</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["listen queue",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
            </graph_items>
        </graph>
        <graph>
            <name>php-fpm Processes</name>
            <width>900</width>
            <height>200</height>
            <yaxismin>0.0000</yaxismin>
            <yaxismax>100.0000</yaxismax>
            <show_work_period>1</show_work_period>
            <show_triggers>1</show_triggers>
            <type>0</type>
            <show_legend>1</show_legend>
            <show_3d>0</show_3d>
            <percent_left>0.0000</percent_left>
            <percent_right>0.0000</percent_right>
            <ymin_type_1>0</ymin_type_1>
            <ymax_type_1>0</ymax_type_1>
            <ymin_item_1>0</ymin_item_1>
            <ymax_item_1>0</ymax_item_1>
            <graph_items>
                <graph_item>
                    <sortorder>0</sortorder>
                    <drawtype>0</drawtype>
                    <color>C80000</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["total processes",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
                <graph_item>
                    <sortorder>1</sortorder>
                    <drawtype>0</drawtype>
                    <color>00C800</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["active processes",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
                <graph_item>
                    <sortorder>2</sortorder>
                    <drawtype>0</drawtype>
                    <color>0000C8</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["idle processes",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
            </graph_items>
        </graph>
        <graph>
            <name>php-fpm Slow Requests / sec</name>
            <width>900</width>
            <height>200</height>
            <yaxismin>0.0000</yaxismin>
            <yaxismax>100.0000</yaxismax>
            <show_work_period>1</show_work_period>
            <show_triggers>1</show_triggers>
            <type>0</type>
            <show_legend>1</show_legend>
            <show_3d>0</show_3d>
            <percent_left>0.0000</percent_left>
            <percent_right>0.0000</percent_right>
            <ymin_type_1>0</ymin_type_1>
            <ymax_type_1>0</ymax_type_1>
            <ymin_item_1>0</ymin_item_1>
            <ymax_item_1>0</ymax_item_1>
            <graph_items>
                <graph_item>
                    <sortorder>0</sortorder>
                    <drawtype>0</drawtype>
                    <color>C80000</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["slow requests",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
            </graph_items>
        </graph>
    </graphs>
</zabbix_export>

Debian 7 (Wheezy)安装配置Apache mod_fastcgi PHP-FPM

本文介绍如何在Debian 7系统上配置和安装使用Apache mod_fastcgi和PHP-FPM。 Apache的默认配置使用mod_php而不是mod_fastcgi,mod_php使用大量的系统资源。
mod_php使用更多资源的主要原因是因为它即使为非PHP文件(如纯HTML和JavaScript文件)也加载。 FastCGI进程管理器(PHP-FPM)通过强制Web服务器充当代理并且仅将以php文件扩展名结尾的文件传递给PHP-FPM来帮助减少所使用的系统资源量。
此外,使用PHP-FPM允许将每个虚拟主机配置为作为单独用户运行PHP代码。 以前,这只能通过使用suPHP。

安装mod_fastcgi和PHP-FPM

mod_fastcgi和PHP-FPM都在Debian 7官方软件库,安装方法如下:
1.更新软件库

  1. sudo apt-get update && sudo apt-get upgrade –show-upgraded

2.看看mod_fastcgi是否可用。 默认情况下,Debian 7不包括安装mod_fastcgi所需的软件库,因为它是一个contrib模块,并且是non-free的(就Debian的许可限制而言)。

  1. sudo apt-cache search libapache2-mod-fastcgi

3.如果不可用,您需要编辑/etc/apt/sources.list文件,以允许将contrib和non-free软件加载到软件库列表中。 您的源文件应如下所示:
/etc/apt/sources.list:

  1. deb http://ftp.es.debian.org/debian stable main contrib non-free
  2. deb-src http://ftp.es.debian.org/debian stable main contrib non-free
  3.  
  4. deb http://ftp.debian.org/debian/ wheezy-updates main contrib non-free
  5. deb-src http://ftp.debian.org/debian/ wheezy-updates main contrib non-free
  6.  
  7. deb http://security.debian.org/ wheezy/updates main contrib non-free
  8. deb-src http://security.debian.org/ wheezy/updates main contrib non-free

4.更新apt-get软件库

  1. sudo apt-get update && sudo apt-get upgrade –show-upgraded

5.安装mod_fastcgi和PHP-FPM

  1. sudo apt-get install libapache2-mod-fastcgi php5-fpm

配置Apache使用PHP-FPM

我们现在将配置Apache将PHP文件的所有请求(带有PHP文件扩展名)通过FastCGI传递给PHP wrapper。
1.激活mod_actions模块

  1. sudo a2enmod actions

2.配置PHP-FPM使用UNIX套接字而不是TCP。 在这个命令中,我们将使用grep来确定套接字是否已被使用。

  1. sudo grep -E ‘^s*listens*=s*[a-zA-Z/]+’ /etc/php5/fpm/pool.d/www.conf

你会看到如下输出:
listen = /var/run/php5-fpm.sock
如果你看到如上输出,请跳到第6步。
3.如果没有看到以上输出,更改如下文件:
etc/php5/fpm/pool.d/www.conf

  1. listen = /var/run/php5-fpm.sock

4.找到如下行并删除
/etc/php5/fpm/pool.d/www.conf:

  1. listen = 127.0.0.1:9000

5.重启php5-fpm生效配置

  1. sudo service php5-fpm restart

6.检查Apache版本

  1. apache2 -v

7.根据Apache版本,编辑对应的文件
Apache 2.2或更早版本
/etc/apache2/mods-enabled/fastcgi.conf:

  1. <IfModule mod_fastcgi.c>
  2.  AddType application/x-httpd-fastphp5 .php
  3.  Action application/x-httpd-fastphp5 /php5-fcgi
  4.  Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
  5.  FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization
  6. </IfModule>

Apache 2.4或更高版本
/etc/apache2/mods-enabled/fastcgi.conf

  1. <IfModule mod_fastcgi.c>
  2.  AddType application/x-httpd-fastphp5 .php
  3.  Action application/x-httpd-fastphp5 /php5-fcgi
  4.  Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
  5.  FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization
  6.  <Directory /usr/lib/cgi-bin>
  7.   Require all granted
  8.  </Directory>
  9. </IfModule>

8.保存文件并检查配置错误

  1. sudo apache2ctl configtest

9.只要你看到Syntax OK输出,重启Apache服务

  1. sudo service apache2 restart

如果没有看到Syntax OK,检查下配置哪里出错了
10.通过创建和访问具有phpinfo()显示的页面来检查PHP是否正常工作。 以下命令将在/var/www(Apache中网站的默认目录)中创建info.php:

  1. sudo echo "<?php phpinfo(); ?>" > /var/www/info.php

Zabbix监控Memcached PHP-FPM Tomcat Nginx MySQL 网站日志

Zabbix作为监控软件非常的灵活,支持的数据类型非常丰富,比如数字(无正负),数字(浮点),日志,文字等。我们需要做的就是使用脚本来收集好数据,然后zabbix收集并画图,设置告警线。这里我们来学习使用Zabbix监控Memcached、PHP-FPM、Tomcat、Nginx、MySQL及网站日志。

 

Memcached监控

 

自定义键值

 

  1. UserParameter=memcached.stat[*],/data/sh/memcached-status.sh "$1"

memcached-status.sh脚本内容为:

  1. #!/bin/bash
  2.  
  3. item=$1
  4. ip=127.0.0.1
  5. port=11211
  6. (echo "stats";sleep 0.5) | telnet $ip $port 2>/dev/null | grep "STAT $itemb" | awk ‘{print $3}’

 

导入模板

 

memcached zabbix模板下载

 

PHP-FPM监控

 

配置php-fpm状态页

 

打开php-fpm.conf配置文件,添加如下配置后重启php:

  1. pm.status_path = /fpm_status

 

自定义键值

 

  1. UserParameter=php-fpm[*],/data/sh/php-fpm-status.sh "$1"

php-fpm-status.sh脚本内容:

  1. #!/bin/bash
  2. ##################################
  3. # Zabbix monitoring script
  4. #
  5. # php-fpm:
  6. #  – anything available via FPM status page
  7. #
  8. ##################################
  9. # Contact:
  10. [email protected]
  11. ##################################
  12. # ChangeLog:
  13. #  20100922        VV        initial creation
  14. ##################################
  15.  
  16. # Zabbix requested parameter
  17. ZBX_REQ_DATA="$1"
  18.  
  19. # FPM defaults
  20. URL="http://localhost/fpm_status"
  21. WGET_BIN="/usr/bin/wget"
  22.  
  23. #
  24. # Error handling:
  25. #  – need to be displayable in Zabbix (avoid NOT_SUPPORTED)
  26. #  – items need to be of type "float" (allow negative + float)
  27. #
  28. ERROR_NO_ACCESS_FILE="-0.9900"
  29. ERROR_NO_ACCESS="-0.9901"
  30. ERROR_WRONG_PARAM="-0.9902"
  31. ERROR_DATA="-0.9903" # either can not connect /        bad host / bad port
  32.  
  33. # save the FPM stats in a variable for future parsing
  34. FPM_STATS=$($WGET_BIN -q $URL -O – 2> /dev/null)
  35.  
  36. # error during retrieve
  37. if [ $? -ne 0 -o -z "$FPM_STATS" ]; then
  38.   echo $ERROR_DATA
  39.   exit 1
  40. fi
  41.  
  42. #
  43. # Extract data from FPM stats
  44. #
  45. RESULT=$(echo "$FPM_STATS" | sed -n -r "s/^$ZBX_REQ_DATA: +([0-9]+)/1/p")
  46. if [ $? -ne 0 -o -z "$RESULT" ]; then
  47.     echo $ERROR_WRONG_PARAM
  48.     exit 1
  49. fi
  50.  
  51. echo $RESULT
  52.  
  53. exit 0

 

导入模板

 

php-fpm zabbix模板下载

 

Tomcat监控

 

刚开始决定监控Tomcat时,使用的是JMX,不过这货设置太复杂了,而且对防火墙要求还挺高,需要开放几个端口。只好使用Tomcat自带的状态页来监控了。

 

自定义键值

 

  1. UserParameter=tomcat.status[*],/data/sh/tomcat-status.py $1

因为需要解析到xml,所以还是决定用python实现比较方便。
/data/sh/tomcat-status.py脚本内容:

  1. #!/usr/bin/python
  2. import urllib2
  3. import xml.dom.minidom
  4. import sys
  5.  
  6. url = ‘http://127.0.0.1:8080/manager/status?XML=true’
  7. username = ‘username’
  8. password = ‘password’
  9.  
  10. passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
  11. passman.add_password(None, url, username, password)
  12. authhandler = urllib2.HTTPBasicAuthHandler(passman)
  13. opener = urllib2.build_opener(authhandler)
  14. urllib2.install_opener(opener)
  15. pagehandle = urllib2.urlopen(url)
  16. xmlData = pagehandle.read()
  17. doc = xml.dom.minidom.parseString(xmlData) 
  18.  
  19. item = sys.argv[1]
  20.  
  21. if item == "memory.free":
  22. print  doc.getElementsByTagName("memory")[0].getAttribute("free")
  23. elif item == "memory.total":
  24. print  doc.getElementsByTagName("memory")[0].getAttribute("total")
  25. elif item == "memory.max":
  26. print  doc.getElementsByTagName("memory")[0].getAttribute("max")
  27. elif item == "threadInfo.maxThreads":
  28. print  doc.getElementsByTagName("threadInfo")[0].getAttribute("maxThreads")
  29. elif item == "threadInfo.currentThreadCount":
  30. print  doc.getElementsByTagName("threadInfo")[0].getAttribute("currentThreadCount")
  31. elif item == "threadInfo.currentThreadsBusy":
  32. print  doc.getElementsByTagName("threadInfo")[0].getAttribute("currentThreadsBusy")
  33. elif item == "requestInfo.maxTime":
  34. print  doc.getElementsByTagName("requestInfo")[0].getAttribute("maxTime")
  35. elif item == "requestInfo.processingTime":
  36. print  doc.getElementsByTagName("requestInfo")[0].getAttribute("processingTime")
  37. elif item == "requestInfo.requestCount":
  38. print  doc.getElementsByTagName("requestInfo")[0].getAttribute("requestCount")
  39. elif item == "requestInfo.errorCount":
  40. print  doc.getElementsByTagName("requestInfo")[0].getAttribute("errorCount")
  41. elif item == "requestInfo.bytesReceived":
  42. print  doc.getElementsByTagName("requestInfo")[0].getAttribute("bytesReceived")
  43. elif item == "requestInfo.bytesSent":
  44. print  doc.getElementsByTagName("requestInfo")[0].getAttribute("bytesSent")
  45. else:
  46. print "unsupport item."

这个脚本是监控Tomcat7的,Tomcat6没有试过,应该区别在状态页的url以及管理页面的用户密码设置上。以上脚本可运行需要在tomcat-users.xml里添加用户,至少权限为manager-status。

 

导入模板

 

tomcat zabbix模板下载

 

Nginx监控

 

配置Nginx状态页

 

在nginx配置文件server{}中加入:

  1. location /nginx_status {
  2.     stub_status on;
  3.     access_log off;
  4. }

 

自定义键值

 

  1. UserParameter=nginx[*],/data/sh/nginx-status.sh "$1"

nginx-status.sh脚本内容:

  1. #!/bin/bash
  2. ##################################
  3. # Zabbix monitoring script
  4. #
  5. # nginx:
  6. #  – anything available via nginx stub-status module
  7. #
  8. ##################################
  9. # Contact:
  10. [email protected]
  11. ##################################
  12. # ChangeLog:
  13. #  20100922        VV        initial creation
  14. ##################################
  15.  
  16. # Zabbix requested parameter
  17. ZBX_REQ_DATA="$1"
  18. ZBX_REQ_DATA_URL="$2"
  19.  
  20. # Nginx defaults
  21. URL="http://127.0.0.1/nginx_status"
  22. WGET_BIN="/usr/bin/wget"
  23.  
  24. #
  25. # Error handling:
  26. #  – need to be displayable in Zabbix (avoid NOT_SUPPORTED)
  27. #  – items need to be of type "float" (allow negative + float)
  28. #
  29. ERROR_NO_ACCESS_FILE="-0.9900"
  30. ERROR_NO_ACCESS="-0.9901"
  31. ERROR_WRONG_PARAM="-0.9902"
  32. ERROR_DATA="-0.9903" # either can not connect /        bad host / bad port
  33.  
  34. # save the nginx stats in a variable for future parsing
  35. NGINX_STATS=$($WGET_BIN -q $URL -O – 2> /dev/null)
  36.  
  37. # error during retrieve
  38. if [ $? -ne 0 -o -z "$NGINX_STATS" ]; then
  39.   echo $ERROR_DATA
  40.   exit 1
  41. fi
  42.  
  43. #
  44. # Extract data from nginx stats
  45. #
  46. case $ZBX_REQ_DATA in
  47.   active_connections)   echo "$NGINX_STATS" | head -1             | cut -f3 -d’ ‘;;
  48.   accepted_connections) echo "$NGINX_STATS" | grep -Ev ‘[a-zA-Z]’ | cut -f2 -d’ ‘;;
  49.   handled_connections)  echo "$NGINX_STATS" | grep -Ev ‘[a-zA-Z]’ | cut -f3 -d’ ‘;;
  50.   handled_requests)     echo "$NGINX_STATS" | grep -Ev ‘[a-zA-Z]’ | cut -f4 -d’ ‘;;
  51.   reading)              echo "$NGINX_STATS" | tail -1             | cut -f2 -d’ ‘;;
  52.   writing)              echo "$NGINX_STATS" | tail -1             | cut -f4 -d’ ‘;;
  53.   waiting)              echo "$NGINX_STATS" | tail -1             | cut -f6 -d’ ‘;;
  54.   *) echo $ERROR_WRONG_PARAM; exit 1;;
  55. esac
  56.  
  57. exit 0

 

导入模板

 

nginx zabbix模板下载

 

MySQL监控

 

MySQL的监控,zabbix是默认支持的,已经有现成的模板,现成的键值,我们需要做的只是在/var/lib/zabbix里新建一个.my.cnf文件,内容如下:

  1. [client]
  2. host=127.0.0.1
  3. port=1036
  4. user=root
  5. password=root

 

网站日志监控

 

配置日志格式

 

我们假设你用的web服务器是Nginx,我们添加一个日志格式,如下:

  1. log_format withHost  ‘$remote_addrt$remote_usert$time_localt$hostt$requestt’
  2.                 ‘$statust$body_bytes_sentt$http_referert’
  3.                 ‘$http_user_agent’;

我们使用tab作分隔符,为了方便awk识别列的内容,以防出错。
然后再设置全局的日志,其它server就不需要设置日志了:

  1. access_log  /data/home/logs/nginx/$host.log withHost;

 

定时获取一分钟日志

 

设置一个定时任务:

  1. * * * * * /data/sh/get_nginx_access.sh

脚本内容为:

  1. #!/bin/bash
  2.  
  3. logDir=/data/home/logs/nginx/
  4. logNames=`ls ${logDir}/*.*.log  |awk -F"/" ‘{print $NF}’`
  5.  
  6. for $logName in $logNames;
  7. do
  8. #设置变量
  9. split_log="/tmp/split_$logName"
  10. access_log="${logDir}/$logName"
  11. status_log="/tmp/$logName"
  12.  
  13. #取出最近一分钟日志
  14. tac $access_log  | awk ‘
  15. BEGIN{
  16. FS="t"
  17. OFS="t"
  18. cmd="date -d "1 minute ago" +%H%M%S"
  19. cmd|getline oneMinuteAgo
  20. }
  21. {
  22. $3 = substr($3,13,8)
  23. gsub(":","",$3)
  24. if ($3>=oneMinuteAgo){
  25. print
  26. } else {
  27. exit;
  28. }
  29. }’ > $split_log
  30.  
  31.  
  32. #统计状态码个数
  33. awk -F’t’ ‘{
  34. status[$4" "$6]++
  35. }
  36. END{
  37. for (i in status)
  38. {
  39. print i,status[i]
  40. }
  41. }
  42. ‘ $split_log  > $status_log
  43. done

这个定时任务是每分钟执行,因为我们监控的频率是每分钟。添加这个任务是为了取得最近一分钟各域名的日志,以及统计各域名的所有状态码个数,方便zabbix来获取所需的数据。

 

自定义键值

 

  1. UserParameter=nginx.detect,/data/sh/nginx-detect.sh
  2. UserParameter=nginx.access[*],awk -v sum=0 -v domain=$1 -v code=$2 ‘{if($$1 == domain && $$2 == code ){sum+=$$3} }END{print sum}’ /tmp/$1.log
  3. UserParameter=nginx.log[*],awk -F’t’ -v domain=$1 -v code=$2 -v number=$3 -v sum=0 -v line="" ‘{if ($$4 == domain && $$6 == code ){sum++;line=line$$5"n" }}END{if (sum > number) print line}’ /tmp/split_$1.log | sort | uniq -c | sort -nr | head -10 | sed -e ‘s/^/<p>/’ -e ‘s/$/</p>/’

nginx-detect.sh脚本内容为:

  1. #!/bin/bash
  2.  
  3. function json_head {
  4.     printf "{"
  5.     printf ""data":["
  6. }
  7.  
  8. function json_end {
  9.     printf "]"
  10.     printf "}"
  11. }
  12.  
  13. function check_first_element {
  14.     if [[ $FIRST_ELEMENT -ne 1 ]]; then
  15.         printf ","
  16.     fi
  17.     FIRST_ELEMENT=0
  18. }
  19.  
  20. FIRST_ELEMENT=1
  21. json_head
  22.  
  23. logNames=`ls /data/home/logs/nginx/*.*.log |awk -F"/" ‘{print $NF}’`
  24. for logName in $logNames;
  25. do
  26. while read domain code count;do
  27.         check_first_element
  28.         printf "{"
  29.         printf ""{#DOMAIN}":"$domain","{#CODE}":"$code""
  30.         printf "}"
  31. done < /tmp/$logName
  32. done
  33. json_end

这里我们定义了三个键值,nginx.detect是为了发现所有域名及其所有状态码,nginx.access[*]是为了统计指定域名的状态码的数量,nginx.log[*]是为了测试指定域名的状态码超过指定值时输出排在前十的url。我们监控nginx访问日志用到了zabbix的自动发现功能,当我们增加域名时,不需要修改脚本,zabbix会帮助我们自动发现新增的域名并作监控。

 

配置探索规则

 

添加一个探索规则,用来发现域名及状态码,如图:
监控

 

配置监控项原型

 

监控所有的域名及状态码:
监控
域名状态码404超过200次监控:
监控
域名状态码500超过50次监控:
监控

 

配置触发器

 

404状态码超过200告警:
监控

监控
500状态码超过50告警:
监控