rsync搭建服务实现多节点文件同步

背景与目的

在使用 SLB(负载均衡)架构的网站部署中,为确保多台 Web 服务器之间文件一致性,文中采用 rsync 工具实现定时同步,从而达到:

  • 保证文件同步
  • 实现高可用性与容灾
  • 支持负载均衡下多台 CentOS 服务器的数据一致性

rsync 简介

rsync(remote synchronize)是 Unix/Linux 下的数据同步工具,具备以下特性:

  • 可镜像整个目录结构、保留文件权限、时间戳、软/硬链接等元数据
  • 无需 root 权限即可安装
  • 快速高效:首传全量,后续仅传输差异数据
  • 支持压缩传输,节省带宽
  • 支持 SSH、rcp、Socket 等多种方式传输
  • 支持匿名方式同步

安装 Rsync

检查是否已安装:

1
rpm -qa | grep rsync

安装方式:

使用 yum:

1
yum -y install rsync

源码编译安装:

1
2
./configure
make && make install

架构说明

  • A服务器(100.xxx.xxx.1):主服务器,运行 rsync 守护进程
  • B服务器(100.xxx.xxx.2):客户端,定时拉取 A服务器文件数据

服务器 A 配置

编辑配置文件 /etc/rsyncd.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
strict modes = yes
port = 873
uid = root
gid = root
user chroot = no
max connections = 5
timeout = 600
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
log file = /var/log/rsyncd.log

[eeetb.com-rsyncd]
path = /home/wwwroot
ignore errors
read only = no
list = no
hosts allow = 100.xxx.xxx.2
auth users = root
secrets file = /etc/rsyncd.password

创建密码文件 /etc/rsyncd.password

1
root:123456

修改防火墙规则(开启端口873)

1
-A INPUT -s 100.xxx.xxx.2 -p tcp --dport 873 -j ACCEPT

启动 rsync 服务

1
/usr/bin/rsync --daemon --config=/etc/rsyncd.conf

设置开机启动:

1
echo '/usr/bin/rsync --daemon --config=/etc/rsyncd.conf' >> /etc/rc.local

服务器 B 配置

创建密码文件 /etc/rsyncd.password

1
2
echo '123456' > /etc/rsyncd.password
chmod 600 /etc/rsyncd.password

手动同步命令

1
2
3
/usr/bin/rsync -avzP --delete --progress \
--password-file=/etc/rsyncd.password \
root@100.xxx.xxx.1::eeetb.com-rsyncd /home/wwwroot

设置定时同步任务

编辑 crontab

1
crontab -e

添加任务(每 3 分钟同步一次)

1
2
3
4
5
MAILTO=""
*/3 * * * * /usr/bin/rsync -avzP --delete --progress \
--exclude=排除目录 \
--password-file=/etc/rsyncd.password \
root@100.xxx.xxx.1::eeetb.com-rsyncd /home/wwwroot > /dev/null 2>&1