十二、 nginx+keepalived实现高可用
- 当nginx宕掉后,另一个nginx顶上来
12.1、 安装nginx
- 192.168.154.129服务器和192.168.154.128服务器,分别安装nginx
01 配置文件不改动,只改动index.html
192.168.154.129服务器
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
</head>
<body>
<h1>Welcome to nginx!</h1>
<h1>主服务器 192.168.154.129</h1>
</body>
</html>
192.168.154.128服务器
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
</head>
<body>
<h1>Welcome to nginx!</h1>
<h1>从服务器 192.168.154.128</h1>
</body>
</html>
02 效果如下
12.2、 keepalived安装
- 192.168.154.129服务器和192.168.154.128服务器,分别安装
01、安装前,先执行下面的命令
yum -y install gcc gcc-c++ autoconf automake make
yum -y install zlib zlib-devel openssl openssl-devel pcre pcre-devel
02、解压并安装
wget http://www.keepalived.org/software/keepalived-1.2.18.tar.gz
tar -zxvf keepalived-1.2.18.tar.gz
cd keepalived-1.2.18
./configure --prefix=/usr/local/keepalived/
make && make install
03、添加到系统服务
#创建keepalived配置文件目录
mkdir /etc/keepalived
#拷贝配置文件到/etc/keepalived目录下
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/
#复制keepalived脚本到/etc/init.d/ 目录
cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/
#拷贝keepalived脚本到/etc/sysconfig/ 目录
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
#建立软连接
ln -s /usr/local/keepalived/sbin/keepalived /sbin/
#添加到开机启动
chkconfig keepalived on
#启动命令
service keepalived start
service keepalived stop
service keepalived restart
#查看服务状况
service keepalived status
12.3、 安装killall
yum install -y psmisc
12.4、 配置keepalived
设定129的keepalived为master,128的keepalived为backup,分别看一下两个的配置文件
192.168.154.129服务器
vim /etc/keepalived/keepalived.conf
global_defs {
## 设置lvs的id,在一个网络内唯一
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
## 主机配置,从机为BACKUP
state MASTER
## 网卡名称
interface eth1
virtual_router_id 51
## 权重值,值越大,优先级越高,backup设置比master小,这样就能在master宕机后将backup变为master,而master恢复后就可以回复.
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
## 同一网段虚拟IP
192.168.154.100
}
}
virtual_server 192.168.154.100 80 {
delay_loop 6
lb_algo rr
lb_kind NAT
persistence_timeout 50
protocol TCP
real_server 192.168.154.128 80 {
weight 1
TCP_CHECK{
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}
192.168.154.128服务器
vim /etc/keepalived/keepalived.conf
global_defs {
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state BACKUP
interface eth1
virtual_router_id 51
priority 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.154.100
}
}
virtual_server 192.168.154.100 80 {
delay_loop 6
lb_algo rr
lb_kind NAT
persistence_timeout 50
protocol TCP
real_server 192.168.154.129 80 {
weight 1
TCP_CHECK{
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}
12.5、 重启两台服务器的keepalived
01、重启后效果,并查看虚拟ip
192.168.154.129
ip add show eth1
192.168.154.128
02、关闭129的keepalived,我们发现主机的虚拟ip 192.168.154.100 漂移到 从机
192.168.154.129
ip add show eth1
192.168.154.128