docker容器使用keepalived模拟mysql主备切换

1.使用制作的centos/keepalived镜像,运行两次,生成两个容器
docker run -idt --privileged centos/keepalived init
容器ip分别为 172.17.0.3, 172.17.0.4(通过命令docker inspect [container_id] | grep IP查看)

2.分别进入容器
IP: 172.17.0.3
vim /etc/keepalived/keepalived.conf

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
global_defs {
router_id mysql_master
}
vrrp_script chk_mysql {
script "netstat -lntp | grep 3306"
interval 1
}

vrrp_instance mysql {
state BACKUP
interface eth0 #在容器中执行ifconfig查看
virtual_router_id 210
priority 150
nopreempt
advert_int 1

authentication {
auth_type PASS
auth_pass 1111
}

virtual_ipaddress {
172.17.0.5/16
}

track_script {
chk_mysql
}
}

IP: 172.17.0.4
vim /etc/keepalived/keepalived.conf

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
global_defs {
router_id mysql_slave
}
vrrp_script chk_mysql {
script "netstat -lntp | grep 3306"
interval 1
}

vrrp_instance mysql {
state BACKUP
interface eth0
virtual_router_id 210
priority 150
nopreempt
advert_int 1

authentication {
auth_type PASS
auth_pass 1111
}

virtual_ipaddress {
172.17.0.5/16
}

track_script {
chk_mysql
}
}

3.启动keepalived
systemctl start keepalived
systemctl enable keepalived
image

验证:

  • 停止172.17.0.4中的MySQL服务(systemctl stop mysqld),发现VIP飘到了172.17.0.3上
    image

所遇问题:
1.systemctl status keepalived查看keepalived状态,发现提示Can’t initialize ipvs: Protocol not available
解决方法:加载ip_vs模块(在宿主机执行如下命令)

1
2
modprobe ip_vs
modprobe ip_vs_wrr

查看内核是否加载ip_vs
lsmod | grep ip_vs