• 基于Ubuntu20.04.01

1.主、备节点分别安装

1
2
3
apt-cache search keepalived
keepalived - Failover and monitoring daemon for LVS clusters
apt-get install keepalived

2.主、备节点分别配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
cd /usr/sbin/keepalived
vim /etc/keepalived/keepalived.conf
chmod 644 keepalived.conf

1>主机:

global_defs {
router_id web1
}
vrrp_instance VI_1 {
state MASTER
interface ens33 #ifconfig确定
virtual_router_id 55
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 123456
}
virtual_ipaddress {
192.168.3.200 # 虚拟ip
}
}

virtual_server 192.168.3.200 3306 {
delay_loop 2
#lb_algo rr #LVS算法,用不到,我们就关闭了
#lb_kind DR #LVS模式,如果不关闭,备用服务器不能通过VIP连接主MySQL
persistence_timeout 50 #同一IP的连接60秒内被分配到同一台真实服务器
protocol TCP
real_server 192.168.3.181 3306 { #检测本地mysql,backup也要写检测本地mysql
weight 3
notify_down /etc/keepalived/mysql_down.sh #当mysq服down时,执行此脚本,杀死keepalived实现切换
TCP_CHECK {
connect_timeout 10 #连接超时
nb_get_retry 3 #重试次数
delay_before_retry 3 #重试间隔时间
connect_port 3306
}
}

2>备机:

vim /etc/keepalived/keepalived.conf
chmod 644 keepalived.conf

global_defs {
router_id web2
}
vrrp_instance VI_1 {
state BACKUP
interface ens33 #ifconfig确定
virtual_router_id 55
priority 50
advert_int 1
authentication {
auth_type PASS
auth_pass 123456
}
virtual_ipaddress {
192.168.3.200 # 虚拟ip
}
}

virtual_server 192.168.3.200 3306 {
delay_loop 2
#lb_algo rr #LVS算法,用不到,我们就关闭了
#lb_kind DR #LVS模式,如果不关闭,备用服务器不能通过VIP连接主MySQL
persistence_timeout 50 #同一IP的连接60秒内被分配到同一台真实服务器
protocol TCP
real_server 192.168.3.182 3306 { #检测本地mysql,backup也要写检测本地mysql
weight 3
notify_down /etc/keepalived/mysql_down.sh #当mysq服down时,执行此脚本,杀死keepalived实现切换
TCP_CHECK {
connect_timeout 10 #连接超时
nb_get_retry 3 #重试次数
delay_before_retry 3 #重试间隔时间
connect_port 3306
}
}

3..主、备节点分别添加脚本

1
2
3
vim /etc/keepalived/mysql_down.sh
#!/bin/bash
pkill keepalived

4..主、备节点分别启动

1
/etc/init.d/keepalived start

5.验证

1
2
ip addr在主机上有飘逸IP 3.200
当关闭主机,飘逸IP则出现在备机