Nginx(十二)-- Nginx+keepalived实现高可用

时间:2024-12-22 14:04:49

1.前提

  两台Linux服务器,IP分别为192.168.80.128 和 192.168.80.129,都安装Nginx和keepalived,并启动。

2.配置双机热备

1.将192.168.80.128看作master(主机),将192.168.80.129看作backup(备机)

2.修改128(主)的keepalived配置文件

! Configuration File for keepalived

global_defs {
router_id LVS_DEVEL # 运行keepalived服务器的一个标识
} vrrp_instance VI_1 {
state MASTER
interface eth0 # 通过ifconfig查看此IP对应的网卡
virtual_router_id 51
priority 101 # master权重设置为101,
# master的权重一定要比backup的权重要大,这样就可以保证在master down机后,
# bakup可以立即升级为master,当master回复后,可以重新成为master。
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.80.100 # 虚拟主机的IP,搭建完成后通过此IP访问
}
} virtual_server 192.168.80.100 80 { # 虚拟IP和端口
delay_loop 6
lb_algo rr
lb_kind NAT
persistence_timeout 50
protocol TCP real_server 192.168.80.128 80 { # 真实IP和端口
weight 1 # 权重
TCP_CHECK {
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
connect_port 80 # 健康检查的端口
}
}
}

3.重启128(master)上的keepalived

  service keepalived restart

4.修改129(备)的keepalived配置文件

! Configuration File for keepalived

global_defs {
router_id LVS_DEVEL # 运行keepalived服务器的一个标识
} vrrp_instance VI_1 {
state BACKUP
interface eth0 # 通过ifconfig查看此IP对应的网卡
virtual_router_id 51
priority 100 # backup权重设置为100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.100.100 # 虚拟主机的IP,搭建完成后通过此IP访问
}
} virtual_server 192.168.100.100 80 { # 虚拟IP和端口
delay_loop 6
lb_algo rr
lb_kind NAT
persistence_timeout 50
protocol TCP real_server 192.168.80.129 80 { # 真实IP和端口
weight 1 # 权重
TCP_CHECK {
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
connect_port 80 # 健康检查的端口
}
}
}

5.重启129(backup)上的keepalived

  service keepalived restart

6.在浏览器中访问:http://192.168.80.100/,出现Nginx的欢迎界面,表示成功!当master正常时,只会访问到master,当master 异常时,就会访问backup。

7.停止128(master)上的keepalived,用来模仿master异常

  service keekealived stop

8.在浏览器中访问:http://192.168.80.100/,发现出现Nginx的欢迎界面,即访问backup成功!

3.配置keepalived的日志

1.配置keepalived日志,默认是没有配置的

  vi /etc/sysconfig/keepalived

  Nginx(十二)-- Nginx+keepalived实现高可用

  改为:KEEPALIVED_OPTIONS="-D -d -S 0"

2.配置到系统日志,修改etc/rsyslog.conf中的内容,vim /etc/rsyslog.conf,在文件中增加如下内容,和9对应:

  local0.* /var/log/keepalived.log

3.重启系统日志

  service rsyslog restart

4.重启keepalived

  service keepalived restart

相关文章