keepalived+nginx
准备:
两台虚拟机两个ip131和133,131作为master,133作为backup
下载keeplived和nginx,为啥要为nginx服务实现高可用,在生产环境中,很多企业把nginx当做负载均衡的分发器,它绝对不能出现故障,所以为它实现高可用vip=100
下载:
两台机器都执行yum install -y keepalived
两台机器都安装nginx,其中131上已经编译安装过nginx
133上需要yum安装nginx: yum install -y nginx
开始配置backup131:
设置vip=100,在keeplived中定义,两台机器主从,主挂了从起来启动nginx提供服务,那么从nginx时访问那个ip,解析ip解析到哪儿,从起来从的ip是什么,需要定义共有ip
vim /etc/keepalived/keepalived.confglobal_defs { notification_email { aming@aminglinux.com } notification_email_from root@aminglinux.com smtp_server 127.0.0.1 smtp_connect_timeout 30 router_id LVS_DEVEL}vrrp_script chk_nginx { script "/usr/local/sbin/check_ng.sh" interval 3}vrrp_instance VI_1 { state MASTER interface ens33 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 123456 } virtual_ipaddress { 192.168.188.100 } track_script { chk_nginx }}
131上nginx编辑监控脚本:
vim /usr/local/sbin/check_ng.sh#!/bin/bash#时间变量,用于记录日志d=`date --date today +%Y%m%d_%H:%M:%S`#计算nginx进程数量n=`ps -C nginx --no-heading|wc -l`#如果进程为0,则启动nginx,并且再次检测nginx进程数量,#如果还为0,说明nginx无法启动,此时需要关闭keepalivedif [ $n -eq "0" ]; then /etc/init.d/nginx start n2=`ps -C nginx --no-heading|wc -l` if [ $n2 -eq "0" ]; then echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log systemctl stop keepalived fifi
脚本中最后关闭主的keepalived是为了防止出现脑裂,当主的keepalived停了从的服务会自动起来,如果住的keepalived没有被杀死从的keepalived也起来了,会导致主从争抢资源争抢vip因为都监听vip,域名访问时不知道访问那个机器会出现紊乱,此情况不允许发生。
chmod 755 /usr/local/sbin/check_ng.sh 这里的这个文件自己定义
systemctl start keepalived 131启动服务
查看是否启动:
ps aux | grep keep 启动起来了
ps aux | grep nginx 也启动了
/etc/init.d/nginx stop 现在手动停掉nginx服务
继续查看nginx服务是否会自动加载看nginx日志,less /var/log/messages
开始配置backp133:
首先检查主从防火墙,selinux和firewalld等关闭掉
selinux永久关闭 vi /etc/selinux/config selinux修改此处为disabled,reboot重启生效关闭firewalld:systemctl disable firewalled 先暂停,不让开机启动systemctl stop firewalld 关闭服务关闭iptables:systemctl disable iptablessystemctl stop iptables
配置133keepalived文件:
vim /etc/keepalived/keepalived.confglobal_defs { notification_email { aming@aminglinux.com } notification_email_from root@aminglinux.com smtp_server 127.0.0.1 smtp_connect_timeout 30 router_id LVS_DEVEL}vrrp_script chk_nginx { script "/usr/local/sbin/check_ng.sh" interval 3}vrrp_instance VI_1 { state BACKUP #修改第一处,变成从 interface ens33 virtual_router_id 51 priority 90 #权重90,其他地方都不变 advert_int 1 authentication { auth_type PASS auth_pass 123456 } virtual_ipaddress { 192.168.188.100 } track_script { chk_nginx }}
编写133nginx监控脚本
vim /usr/local/sbin/check_ng.sh#时间变量,用于记录日志d=`date --date today +%Y%m%d_%H:%M:%S`#计算nginx进程数量n=`ps -C nginx --no-heading|wc -l`#如果进程为0,则启动nginx,并且再次检测nginx进程数量,#如果还为0,说明nginx无法启动,此时需要关闭keepalivedif [ $n -eq "0" ]; then systemctl start nginx n2=`ps -C nginx --no-heading|wc -l` if [ $n2 -eq "0" ]; then echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log systemctl stop keepalived fifi
此时关闭131nginx会自动重启
此时访问100会访问到131上去,这里并没有负载均衡
关闭131的keepalived,133的keepalived启动进入工作状态