vrrp_instance VI_1 {
state BACKUP
interface eth0 #根据实际网络接口进行更改
virtual_router_id 51
priority 90 #优先级,backup设置为90
advert_int 1
#nopreempt #主动抢占资源
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.30
}
}
virtual_server 192.168.1.30 3306 {
delay_loop 2
#lb_algo rr
#lb_kind NAT
persistence_timeout 50
protocol TCP
real_server 192.168.1.20 3306 { #检测本地mysql
weight 3
notify_down /tmp/mysql.sh #当mysql服务down时,执行此脚本,杀死keepalived实现切换
TCP_CHECK {
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
}
}
}
master 和 backup上编辑mysql.sh
# vim /tmp/mysql.sh
#!/bin/bash
pkill keepalived
# chmod +x !$
# systemctl start keepalived
两台mysql服务器授权允许root远程登录:
# mysql -uroot -p123456789
mysql> grant all on *.* to 'root'@'192.168.1.%' identified by '123456';
mysql> flush privileges;
测试高可用
通过mysql客户端通过VIP连接,看是否连接成功。
这里我用同网段的另一台机器,连接测试:
# mysql -h192.168.1.30 -uroot -p123456
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select * from test.user;
+--------+------+
| number | name |
+--------+------+
| 1 | testid |
+--------+------+
1 row in set (0.01 sec)
---------------------
可以看到,连接成功,且查询数据没有问题,停止master上mysql服务,是否能正常切换到backup上,可以使用 ip addr命令来查看VIP在哪台服务器上。
master上查看是否有VIP,可以看到VIP在master上
# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:cf:ab:c4 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.10/24 brd 192.168.1.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet 192.168.1.30/32 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::fe8e:3c2f:4d32:e9fd/64 scope link noprefixroute
valid_lft forever preferred_lft forever
---------------------
停掉master上mysql服务:
# systemctl stop mysqld
# ps axu |grep keepalived
root 11074 0.0 0.0 112708 988 pts/1 S+ 15:28 0:00 grep --color=autokeepalived
# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:cf:ab:c4 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.10/24 brd 192.168.1.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::fe8e:3c2f:4d32:e9fd/64 scope link noprefixroute
valid_lft forever preferred_lft forever
---------------------
可以看到,keepalived在mysql服务停掉之后也被停掉,VIP不在master上。
backup上查看是否有VIP,可以看到VIP在backup上。