大约三个月前 Ricky 写过同样的一篇文章,那篇文章是检测 node.js 服务的,详情请见:《使用 Linux Shell 脚本定时监控 web 服务(进程挂掉自动重启服务和检测首页是否能返回状态码 200 )》,本篇文章检测的是 nginx 和 resin 服务(什么是 resin ?resin 与 tomcat 是类似的,您就把它当做 tomcat 来看待就好了)。但两篇文章大同小异,主要是介绍一些 Linux Shell 编程的相关方法和思路。
最近 Ricky 这边又有一个需求,当检测到服务器(操作系统依旧为:CentOS Linux )上的 nginx 和 resin 进程挂掉或者工作不稳定(比如数据库频繁连接失败)后,自动重启 nginx 和 resin 的进程。当然,这里需要自己用 Java 写一个接口,这个接口会去检查 resin 和数据库是否还在正常工作,本篇文章以接口 http://127.0.0.1/check.jsp 为例。
Linux Shell 脚本主要实现以下功能:
- 每 30 秒检测一次;
- 当检测到进程挂掉时,自动重启相关进程;
- 当检测到接口 http://127.0.0.1/check.jsp 返回的字符串不是 ok 时,自动重启相关进程;
- 将自动重启的时间和原因记录到日志文件中。
部署:
1 、编写脚本,在命令行界面输入:
[root@host ~]# vi /root/port.sh
键入小写字母 i ,进入编辑模式,将以下脚本复制粘贴进去(请根据实际需要进行相应地修改):
#!/bin/bash # 加载环境变量 source /etc/profile # nginx 和 resin 监听的端口号为 80 和 8080 ,检查 80 和 8080 端口是否有进程在监听 port=`netstat -ntlp | grep -cE ":8080|:80"` #echo $port # 如果 80 或 8080 端口没有进程在监听 if [ "$port" = "0" -o "$port" = "1" ]; then # 则重新启动 nginx 和 resin 的进程 /usr/java/resin/bin/httpd.sh restart /etc/init.d/nginx restart # 将日志写入日志文件 echo $(date "+%F %H:%M:%S") - already restart port - process not found >> /root/port.log # 如果 80 或 8080 端口有进程在监听 else # 访问接口 code=`curl http://127.0.0.1/check.jsp` # 如果返回的字符串不是 ok if [ "$code" != "ok" ]; then # 则重新启动 nginx 和 resin 的进程 /usr/java/resin/bin/httpd.sh restart /etc/init.d/nginx restart # 将日志写入日志文件 echo $(date "+%F %H:%M:%S") - already restart port - check fail ! >> /root/port.log fi fi
按一次 ESC 键退出编辑模式,然后键入 “ :wq ” 保存并退出。
2 、……
剩余的步骤请参见这篇文章:《使用 Linux Shell 脚本定时监控 web 服务(进程挂掉自动重启服务和检测首页是否能返回状态码 200 )》
日志格式说明:
[root@host ~]# cat /root/port.log 2018-09-18 11:50:04 - already restart port - process not found 2018-09-18 11:52:37 - already restart port - check fail ! [root@host ~]#
日志格式为:时间 – already restart port – 重启原因,其中重启原因有两种:
- process not found :检测到相关进程不存在;
- check fail !:接口 http://127.0.0.1/check.jsp 返回的字符串不是 ok 。
其他相关文章:
发表评论?