centos7安装配置keepalived+nginx
安装keepalived
主从服务器已安装好nginx,ip分别为
192.168.254.130 主
192.168.254.128 从
采用yum方式安装,主从分别运行
yum install keepalived
启动keepalived
systemctl start keepalived.service
设置开机启动
systemctl enable keepalived.service
配置keepalived
主配置/etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
script_user root
enable_script_security
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2 每两秒检测一次
weight -20 当返回值不为0时权重减20
}
vrrp_instance VI_1 {
state MASTER # 标识为主服务
interface ens33 #绑定对应的网卡名称
virtual_router_id 61 # 虚拟路由id,和从机保持一致
mcast_src_ip 192.168.254.130 #本机ip
priority 101 #权重,需要高于从机
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx ## 执行 Nginx 监控的服务
}
virtual_ipaddress {
192.168.254.125/24 #VIP地址
}
notify_master /etc/keepalived/sendemail.py 邮件发脚步
}
从配置/etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
script_user root
enable_script_security
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2 每两秒检测一次
weight -20 当返回值不为0时权重减20
}
vrrp_instance VI_1 {
state BACKUP # 标识为从服务
interface ens33 #绑定对应的网卡名称
virtual_router_id 61 # 虚拟路由id,和主机机保持一致
mcast_src_ip 192.168.254.128 #本机ip
priority 90 #权重,需要低于主机
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx ## 执行 Nginx 监控的服务
}
virtual_ipaddress {
192.168.254.125/24 #VIP
}
notify_master /etc/keepalived/sendemail.py 邮件发脚步
}
nginx监控脚步/etc/keepalived/nginx_check.sh 给执行权限
#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
exit 1
fi
exit 0
邮件发送脚步/etc/keepalived/sendemail.py 给执行权限
#!/usr/bin/python
# encoding: utf-8
import sys
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
reload(sys)
sys.setdefaultencoding('utf8')
mail_to_list = ['xxx@163.com']
# mail_to_list = ['xxx@163.com', 'xxx@163.com']
# mail_cc_list = []
mail_cc_list = []
#mail_host = 'mail.xx.com'
mail_host = '192.168.xxx.xx'
mail_port = 465
mail_user = 'forsend@163.com'
mail_pass = 'passwordxxx'
def send_mail(to_list, cc_list, sub, content):
me = mail_user
msg = MIMEMultipart('alternative')
html_part = MIMEText(content, 'html', 'utf-8')
msg.attach(html_part)
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ';'.join(to_list)
msg['Cc'] = ';'.join(cc_list)
receiver = to_list
receiver.extend(cc_list)
try:
s = smtplib.SMTP_SSL()
s.connect(mail_host, mail_port)
s.login(mail_user, mail_pass)
s.sendmail(me, receiver, msg.as_string())
s.close()
return True
except Exception, e:
print str(e)
return False
host_name = os.uname()[1]
sub = 'keepalive start on {}'.format(host_name)
content = '<html><body><p>keepalive start on {}</p></body></html>'.format(host_name)
send_mail(mail_to_list, mail_cc_list, sub, content)