Keepalived - Docker 搭建 Keepalived 主从节点服务
Docker 搭建 Keepalived 主从节点服务
Keepalived 离线镜像包
链接: https://pan.baidu.com/s/15Q1UKDntg6OqUyVZRW-DlA 提取码: n5ch
搭建过程
创建文件路径并分配权限
sudo mkdir -p /usr/local/keepalived.2.1.5 sudo chmod 777 /usr/local/keepalived.2.1.5
将docker镜像文件包centos-keepalived-img.tar放至/usr/local/keepalived.2.1.5路径下,加载本地文件到镜像
sudo docker load --input /usr/local/keepalived.2.1.5/centos-keepalived-img.tar
创建文件夹,并分配权限
sudo mkdir -p /usr/local/keepalived.2.1.5/conf/ sudo mkdir -p /usr/local/keepalived.2.1.5/log/ sudo chmod 777 /usr/local/keepalived.2.1.5/conf/ sudo chmod 777 /usr/local/keepalived.2.1.5/log/
查看物理网卡名,当前使用的ip挂在哪个网卡下面,后面配置文件里面就写哪个网卡名
ifconfig
创建配置文件
sudo vi /usr/local/keepalived.2.1.5/conf/keepalived.conf
以下为文件内容:
! Configuration File for keepalived # 定义检查脚本 vrrp_script check_haproxy { script "/etc/keepalived/check_haproxy.sh" interval 3 } global_defs { # 路由id:当前安装keepalived的节点主机标识符,保证全局唯一。 router_id xxxx # 组播地址,修改最后一位和VIP最后一位相同即可 vrrp_mcast_group4 224.0.0.10 } vrrp_instance VI_1 { #网卡名称(当前物理机使用的主要网卡) interface eth0 #节点定义 MASTER / BACKUP state MASTER #主从集群之间的虚拟路由id必须一致,同一组集群vid唯一。基于规范性要求,设置为虚拟iP最后一位(如8) virtual_router_id 10 # 100 on master, 50 on backup. 主从尽量相差50 priority 100 virtual_ipaddress { #定义虚拟ip。需要定义一个同一子网下未被分配的ip xx.xx.xx.xx } authentication { auth_type PASS #定义认证密码,主从集群之间的认证必须一致 auth_pass s3cr3t } # 执行检查脚本(选配) track_script { check_haproxy } }
修改配置文件权限
chmod 644 keepalived.conf
创建haproxy运行状态监控脚本(选配)
vim /usr/local/keepalived.2.1.5/conf/check_haproxy.sh
以下为文件内容:
#!/bin/bash # 使用curl向haproxy发送HTTP请求,-I选项仅返回响应头信息 response=$(curl -I http://haproxy的ip:8888/status) # 检查 CURL 命令的退出状态码 if [ $? -ne 0 ]; then echo "CURL request failed." exit 2 # 返回退出状态码 2 表示请求失败 fi # 检查响应是否包含 "Connection refused" if [[ $response == *"Connection refused"* ]]; then echo "Connection refused found." exit 1 # 返回退出状态码 1 表示连接被拒绝 fi # 默认情况下,返回退出状态码 0 表示成功 echo "HTTP Status 200 OK found." exit 0
修改脚本文件权限
chmod 777 check_haproxy.sh
创建keepalived启动文件并编辑文件内容
sudo vi /usr/local/keepalived.2.1.5/keepalivedcluster.sh
文件内容:
sudo docker run -it -d \ --network=host --privileged=true \ --cap-add NET_ADMIN \ -v /usr/local/keepalived.2.1.5/conf:/etc/keepalived/ \ -v /usr/local/keepalived.2.1.5/log:/var/log/ \ --name centos-keepalived centos-keepalived-img:latest /usr/sbin/init
执行sh文件,启动容器
sudo sh /usr/local/keepalived.2.1.5/keepalivedcluster.sh
验证
查看/启动keepalived服务
docker exec -it centos-keepalived bash #进入容器
systemctl status keepalived.service #查看keepalived是否启动
systemctl start keepalived.service #若未启动,执行该命令;若已启动,跳过该命令
验证:在其他客户端上,使用虚拟ip访问keepalived所在服务器的服务
日志查看(宿主机查看):
#查容器message日志全部内容 sudo cat /usr/local/keepalived.2.1.5/log/messages # 只查keepalived相关日志 sudo tail -1000f /usr/local/keepalived.2.1.5/log/messages |grep 'Keep\| keep'
日志查看(容器内查看):
docker exec -it centos-keepalived bash #进入容器
journalctl -u keepalived.service #查看日志
使用以下命令监控当前网卡的vrrp协议通讯,可以看到keepalived主节点ip在一直和配置的组播地址进行通信。当主节点停止时,从节点开始与组播地址进行通信。
tcpdump -i 网卡名 vrrp -n