Home  >  Article  >  Backend Development  >  PHP脚本监控Nginx 502异常并自动重启php-fpm

PHP脚本监控Nginx 502异常并自动重启php-fpm

WBOY
WBOYOriginal
2016-06-13 12:19:421079browse

PHP脚本监控Nginx 502错误并自动重启php-fpm

服务器时不时出现Nginx 502 Bad Gateway,如果在电脑旁边还好,要是半夜或者出去了,怎么办?

没关系,写个脚本检测服务状态,发现异常,自动重启。

自动重启脚本:

 

<span style="color: #000000;">php </span><span style="color: #800080;">$url</span> = 'http://blog.rebill.info'<span style="color: #000000;">; </span><span style="color: #800080;">$cmd</span> = '/usr/local/php/sbin/php-fpm restart'<span style="color: #000000;">;   </span><span style="color: #0000ff;">for</span>(<span style="color: #800080;">$i</span> = 0; <span style="color: #800080;">$i</span> $i ++<span style="color: #000000;">){         </span><span style="color: #800080;">$exec</span> = "curl  connect-timeout 3 -I <span style="color: #800080;">$url</span> 2>/dev/null"<span style="color: #000000;">;         </span><span style="color: #800080;">$res</span> = <span style="color: #008080;">shell_exec</span>(<span style="color: #800080;">$exec</span><span style="color: #000000;">);           </span><span style="color: #0000ff;">if</span>(<span style="color: #008080;">stripos</span>(<span style="color: #800080;">$res</span>, '502 Bad Gateway') !== <span style="color: #0000ff;">false</span><span style="color: #000000;">){                 </span><span style="color: #008080;">shell_exec</span>(<span style="color: #800080;">$cmd</span><span style="color: #000000;">);                 </span><span style="color: #0000ff;">exit</span><span style="color: #000000;">();         } }</span>

原理就是用curl获取HTTP头,发现502状态码就执行重启php-fpm的命令。

url和cmd根据实际情况改成自己的。然后放到crontab里一分钟执行一次。

 

*/<span style="color: #800000;">1</span> * * * * /usr/bin/php /root/crontab/nginx502.php

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn