shell脚本监控php-fpm并自动重启服务

监控php-fpm并自动重启服务的shell脚本,脚本的主要功能:不断检查网站的状态,如果异常就重启php-fpm服务

脚本代码:
#!/bin/bash
#变量初始化
process="php-fpm" #进程名
startCmd="/etc/init.d/php-fpm start" #启动命令
down=0

while true
do
    #取得http状态码
    code=$(curl -H "Host:www.jb51.net" -m 5 -L -s -w %{http_code} http://127.0.0.1 -o /dev/null)
    #当状态码返回000或者大于等于500时,计数故障到down变量
    if [ $code -eq 000 -o $code -ge 500 ];then
        ((down++))
    else
break
    fi
    #稍等5s
    sleep 5
    #判断是否连续检测三次都为故障.
    if [ $down -ge 3 ];then
if [ "$(find /tmp/${process}_restart -mmin -3)" == "" ];then
                #取得进程名对应的所有pid
pids=$(ps aux | grep ${process} | grep -v "grep" | awk '{print $2}')
                #依次对所有pid执行kill命令
for i in $pids;do
kill -9 $i
kill -9 $i
done
                #kill完pid后,启动服务
$startCmd
echo "$(date) Return code $code,${process} had been restarted" >> /tmp/${process}_restart
else
echo "$(date) ${process} not yet recovery.As it had been restarted in 2 minutes.so this time ignore." >> /tmp/${process}_not_restart
fi

break
    fi
done

大家都知道PHP-FPM内置了状态页,开启后可查看PHP-FPM的详细运行状态,给PHP-FPM优化带来帮助。

打开php-fpm.conf,配置php-fpm状态页选项

1

pm.status_path = /phpfpm_status

配置nginx.conf,添加可访问server

1

2

3

4

5

6

7

8

9

server {

  listen 80;

  server_name 127.0.0.1;

  location /phpfpm_status {

    fastcgi_pass 127.0.0.1:9000;

    include fastcgi_params;

    fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;

  }

}

重启或重载nginx,和php-fpm

1

2

service php-fpm restart

service nginx restart

浏览器访问结果:

curl http://127.0.0.1/phpfpm_status

可通过带不同参数查看php-fpm status输出格式:

1

2

3

4

5

6

7

8

9

10

http://www.foo.bar/status #默认纯文本

http://www.foo.bar/status?json #json格式

http://www.foo.bar/status?html #html格式

http://www.foo.bar/status?xml #xml格式

  

#full参数可查看进程详细信息

http://www.foo.bar/status?full

http://www.foo.bar/status?json&full

http://www.foo.bar/status?html&full

http://www.foo.bar/status?xml&full

PHP-FPM status参数说明:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

pool – fpm池子名称,大多数为www

process manager – 进程管理方式,值:static, dynamic or ondemand. dynamic

start time – 启动日期,如果reload了php-fpm,时间会更新

start since – 运行时长

accepted conn – 当前池子接受的请求数

listen queue – 请求等待队列,如果这个值不为0,那么要增加FPM的进程数量

max listen queue – 请求等待队列最高的数量

listen queue len – socket等待队列长度

idle processes – 空闲进程数量

active processes – 活跃进程数量

total processes – 总进程数量

max active processes – 最大的活跃进程数量(FPM启动开始算)

max children reached - 大道进程最大数量限制的次数,如果这个数量不为0,那说明你的最大进程数量太小了,请改大一点。

slow requests – 启用了php-fpm slow-log,缓慢请求的数量

猜你喜欢

转载自blog.csdn.net/bbwangj/article/details/81321174