用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
# keepalived与nginx联动-监控 [TOC] ## 一、目的和方法 目的 * nginx反向代理服务停止,keepalived服务也停止 方法 * 直接停止 监控到nginx挂掉后,停止keepalived来实现VIP漂移 * 拯救一次再停止 监控到nginx挂掉后,重启nginx,若启动不成功, 停止keepalived来实现VIP漂移 * 权重降级 监控到nginx挂掉后,减少权重并重启nginx,主权重小于从时,进行keepalived主备切换,达到VIP漂移 ## 二、方法1[直接停止] ### 1.编写nginx监控脚本 ```sh cat >/server/scripts/check_web.sh <<"EOF" #!/bin/bash web_info=$(ps -ef|grep [n]ginx|wc -l) if [ $web_info -lt 2 ] then /etc/init.d/keepalived stop fi EOF ``` ### 2.授予权限 ```sh chmod +x /server/scripts/check_web.sh ``` ### 3.运行脚本,实现监控nginx服务 编辑keepalived服务配置文件 ```sh vim /etc/keepalived/keepalived.conf vrrp_script check_web { script "/server/scripts/check_web.sh" interval 2 weight 2 } track_script { check_web } ``` ## 三、方法2[拯救一次] ### 1.编写nginx监控脚本 ```sh cat >/server/scripts/check_web.sh <<"EOF" #!/bin/bash web_info_1=$(ps -ef|grep [n]ginx|wc -l) if [ $web_info_1 -lt 2 ];then /etc/init.d/nginx start sleep 2 web_info_2=$(ps -ef|grep [n]ginx|wc -l) if [ $web_info_2 -lt 2 ];then /etc/init.d/keepalived stop fi fi EOF ``` ### 2.授予权限 ```sh chmod +x /server/scripts/check_web.sh ``` ### 3.运行脚本,实现监控nginx服务 编辑keepalived服务配置文件 ```sh vim /etc/keepalived/keepalived.conf vrrp_script check_web { script "/server/scripts/check_web.sh" interval 2 weight 2 } track_script { check_web } ``` ## 四、 方法3[降级] ### 1. 编写nginx监控脚本 ```sh cat >/server/scripts/check_web.sh <<"EOF" #!/bin/bash web_info=$(ps -ef|grep [n]ginx|wc -l) if [ $web_info -lt 2 ];then /etc/init.d/nginx start return 1 else return 0 fi EOF ``` ### 2. 授予权限 ```sh chmod +x /server/scripts/check_web.sh ``` ### 3.运行脚本,实现监控nginx服务 [此处假设主从权重分别是101,100] ```sh vim /etc/keepalived/keepalived.conf vrrp_script check_web { script "/server/scripts/check_web.sh" interval 2 weight 2 } track_script { check_web } ``` ### 4. 此方法思路: 每次脚本执行后,keepalived根据返回值,失败返回值1,成功返回0,失败则减小权重,若主权重较少到比备小以后,会进行主从切换 如果后来又检测成功,会增加权重[不超过最大权重],若超过原来的从机,会切换回来 因此,计划减少几次权重后,进行主备切换,就要要保证主的权重,能在连续减几次权重值后,会小于从