CentOS 7 下 Keepalived + Nginx 实现双机高可用
文章目录
- [CentOS 7 下 Keepalived + Nginx 实现双机高可用](#CentOS 7 下 Keepalived + Nginx 实现双机高可用)
-
服务器准备
服务信息
主机名 |
IP |
角色 |
其他 |
my-web01 |
192.168.157.31 |
nginx keepalived |
master |
my-web02 |
192.168.157.32 |
nginx keepalived |
backup |
VIP |
192.168.157.30 |
|
|
服务架构
服务安装
nginx
bash
复制代码
# 所有主机
[root@my-web01 ~]$ yum -y install nginx
Keepalived
bash
复制代码
# 所有主机
[root@my-web01 ~]$ yum -y install keepalived
服务配置
nginx
bash
复制代码
[root@my-web01 ~]$ cat /usr/share/nginx/html/index.html
<!DOCTYPE html>
<h1>my web01 ~~~</h1>
bash
复制代码
[root@my-web02 ~]$ cat /usr/share/nginx/html/index.html
<!DOCTYPE html>
<h1>my web02 ~~~</h1>
Keepalived
bash
复制代码
[root@my-web01 ~]$ cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
vrrp_script check_nginx {
script "killall -0 nginx"
interval 2
}
vrrp_instance VI_1 {
interface ens33
state MASTER
priority 200
virtual_router_id 33
virtual_ipaddress {
192.168.157.30
}
authentication {
auth_type PASS
auth_pass password
}
track_script {
check_nginx
}
}
bash
复制代码
[root@my-web02 ~]$ cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
vrrp_script check_nginx {
script "killall -0 nginx"
interval 2
}
vrrp_instance VI_1 {
interface ens33
state BACKUP
priority 100
virtual_router_id 33
virtual_ipaddress {
192.168.157.30
}
authentication {
auth_type PASS
auth_pass password
}
track_script {
check_nginx
}
}
启动服务
nginx
bash
复制代码
# 所有节点
systemctl start nginx
keepalived
bash
复制代码
# 所有节点
systemctl start nginx
服务验证
查看 VIP 状态
bash
复制代码
# web01 -- 获取 VIP
[root@my-web01 ~]$ ip addr | grep '192.168.157'
inet 192.168.157.31/24 brd 192.168.157.255 scope global ens33
inet 192.168.157.30/32 scope global ens33
# web01 -- 未获取 VIP
[root@my-web02 ~]$ ip addr | grep '192.168.157'
inet 192.168.157.32/24 brd 192.168.157.255 scope global ens33
CURL 命令访问
bash
复制代码
# VIP -- 访问到 web01
[root@my-web01 ~]$ curl 192.168.157.30
<!DOCTYPE html>
<h1>my web01 ~~~</h1>
# web01
[root@my-web01 ~]$ curl 192.168.157.31
<!DOCTYPE html>
<h1>my web01 ~~~</h1>
# web02
[root@my-web01 ~]$ curl 192.168.157.32
<!DOCTYPE html>
<h1>my web02 ~~~</h1>
浏览器访问
高可用验证
停止 web01 下 Nginx
bash
复制代码
# web01
[root@my-web01 ~]$ systemctl stop nginx
bash
复制代码
# web01 -- VIP 漂移
[root@my-web01 ~]$ ip addr | grep '192.168.157'
inet 192.168.157.31/24 brd 192.168.157.255 scope global ens33
# web02 -- 获取 VIP
[root@my-web02 ~]$ ip addr | grep '192.168.157'
inet 192.168.157.32/24 brd 192.168.157.255 scope global ens33
inet 192.168.157.30/32 scope global ens33
恢复 web01 下 Nginx
bash
复制代码
[root@my-web01 ~]$ systemctl start nginx
bash
复制代码
# web01 -- 获取 vip
[root@my-web01 ~]$ ip addr | grep '192.168.157'
inet 192.168.157.31/24 brd 192.168.157.255 scope global ens33
inet 192.168.157.30/32 scope global ens33
# web02 -- vip 漂移
[root@my-web02 ~]$ ip addr | grep '192.168.157'
inet 192.168.157.32/24 brd 192.168.157.255 scope global ens33
参考