1、高可用概念
一台nginx宕机了,还可以切换到另一台nginx上继续工作,让用户继续访问后台服务器
y
2、准备工作
(1)需要两台 nginx 服务器
(2)需要 keepalived
(3)需要虚拟 ip
3、高可用准备工作
(1)需要两台服务器 192.168.17.129 和 192.168.17.131
(2)在两台服务器安装 nginx
这里如果不想再去安装一遍 Nginx ,可以直接克隆 CentOs 。
(3)在两台服务器安装 keepalived
使用命令安装:yum install keepalived –y
安装之后,在 /etc 里面生成目录 keepalived,有文件 keepalived.conf
4、完成高可用配置(主从配置)
(1)主机 Nginx 修改/etc/keepalived/keepalivec.conf
配置文件
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.17.129
smtp_connect_timeout 30
router_id LVS_DEVEL # 主机名字
}
vrrp_script chk_http_port {
script "/usr/local/src/nginx_check.sh"
interval 2 #(检测脚本执行的间隔)
weight 2 # 权重
}
vrrp_instance VI_1 {
state MASTER # 备份服务器上将 MASTER 改为 BACKUP
interface ens33 # 网卡
virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
priority 100 # 主、备机取不同的优先级,主机值较大,备份机值较小
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.77.50 # VRRP H 虚拟地址
}
}
(2)主机 /usr/local/src
添加检测脚本:nginx_check.sh
#!/bin/bash
A=`ps -C nginx –no-header | wc -l`
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
(3) 从机 Nginx修改/etc/keepalived/keepalivec.conf
配置文件
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.17.129
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_http_port {
script "/usr/local/src/nginx_check.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP # 修改为从机 BACKUP
interface ens33 # 修改为从机 ip
virtual_router_id 51
priority 90 # 优先级比主机低
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.77.50
}
}
(4)从机 /usr/local/src
添加检测脚本:nginx_check.sh
#!/bin/bash
A=`ps -C nginx –no-header | wc -l`
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
(5)、启动 Nginx
分别启动主从 Nginx ,切换到/usr/local/nginx/sbin/
,执行./nginx
(6)、主从都启动 keepalived
CentoS6启动命令
service keepalived start
Centos7启动命令
systemctl start keepalived.service
(7)、主从都测试 keepalived 是否启动成功
ps -ef | grep keepalived
5、最终测试
此时便可以通过虚拟 ip 地址访问到 Nginx 。
6、