linux中keepalived实现nginx高可用配置
安装keepalived
运行如下命令即可tar -zxvf keepalived-2.0.8.tar.gz -C /usr/srccd /usr/src/keepalived-2.0.8sudo apt-get install autoconfaclocalautoconfautoheaderautomake --add-missingsudo apt-get install libssl-dev./configure --prefix=/usr/local/keepalivedmake && make installcd /usr/local/keepalived/sbin./keepalivedps -ef | grep keepalived
修改keepalived配置文件
keepalived的作用,基本上是和多台nginx服务器通信,当主服务器宕机,将ip分法给备用服务器例如,写类似如下代码 在你的linux网卡中添加一个ip地址,这个ip地址可以ping通,也就是多个nginx服务器,可以共用这一个ip,通过keepalived决定谁可以拥有这个ip ip addr add yourtestip dev ens33 ip addr ping yourtestip配置keepalived配置文件sudo vim /usr/local/keepalived/etc/keepalived/keepalived.conf ! Configuration File for keepalived global_defs { # 服务器宕机发送通知邮件 notification_email { acassen@firewall.loc } notification_email_from Alexandre.Cassen@firewall.loc smtp_server 192.168.200.1 smtp_connect_timeout 30 router_id LVS_DEVEL vrrp_skip_check_adv_addr vrrp_strict vrrp_garp_interval 0 vrrp_gna_interval 0 } # 虚拟路由器配置 vrrp_instance VI_1 { state MASTER # 设置当前nginx服务器为主节点,备用nginx服务器对应设置成BACKUP即可 interface eth0 # 绑定服务器网卡 virtual_router_id 51 # 主备nginx服务器此id必须一致 priority 100 # 设置优先级,1-254之间,备用服务器的结点优先级设置低点 advert_int 1 # 信息发送间隔,主备都要一致 authentication { # 授权信息,主备服务器一致 auth_type PASS auth_pass 1111 } virtual_ipaddress { # 虚拟IP,主备服务器必须一致,网段必须和nginx一致 192.168.200.16 } notify_master "/usr/local/keepalived/sbin/notify_sh master" # 主服务器宕机,备用服务器要成为主服务器则调用此脚本 notify_backup "/usr/local/keepalived/sbin/notify_sh backup" notify_fault "/usr/local/keepalived/sbin/notify_sh fault" } vrrp_script chk_health { script "[[`ps -ef | grep nginx | grep -v grep | wc -l`-ge 2]] && exit 0 || exit 1" # 判断nginx进程是否大于等于2 interval 1 # 1秒钟执行一次 weight -2 # nginx宕机,本机权重降低2 } track_script { chk_health # 检查nginx }notify_sh脚本 #!/bin/bash case $1 in master) /usr/local/nginx/sbin/nginx exit 0 ;; backup) /usr/local/nginx/sbin/nginx -s stop /usr/local/nginx/sbin/nginx exit 0 ;; fault) /usr/local/nginx/sbin/nginx -s stop exit 0 *) echo "(notify.sh(master|backup|fault)" exit 1 ;; esac