MENU

基于rsync + inotify实现服务器间文件实时同步

September 15, 2021 • 博文

方案说明

首先inotify监控文件系统的各种变化,当文件有任何变动时,就触发rsync同步,则该源服务器为主动,那它就是客户端,备份服务器为被动方,那它就是服务端(-deamon)。如此达到实时同步目的。

实现源服务器文件变动后同步更新至备份服务器

环境说明

服务器均为 Centos7

rsync 安装

yum -y install rsync  
firewall-cmd --add-port=873/tcp --permanent 
firewall-cmd --reload
systemctl start rsyncd.service
systemctl enable rsyncd.service
systemctl status rsyncd.service
netstat -lnp|grep 873

备份服务器(server端 192.168.1.102)

rsync 配置

  • 建立用户与密码认证文件
mkdir -p /etc/rsyncd/
echo "backup:bk_password" > /etc/rsyncd/rsyncd.passwd
chmod 0600 /etc/rsyncd/rsyncd.passwd
  • 建立rsync配置文件
# vi /etc/rsyncd.conf
uid = root
gid = root
use chroot = no
max connections = 4
strict modes = yes
hosts allow = *
port = 873
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log
ignore nonreadable = yes
dont compress   = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2

[test]
path = /opt/test
ignore errors
read only = false
write only = false
list = false
auth users = backup
secrets file = /etc/rsyncd/rsyncd.passwd

PS:注意这里要将 read only 修改为 false, 因为是要将文件同步到该模块的,必须可写

重新启动

systemctl restart rsyncd.service

源服务器 (client端 192.168.1.101)

rsync 安装

  • rsync 安装
yum -y install rsync  
firewall-cmd --add-port=873/tcp --permanent 
firewall-cmd --reload
  • 建立访问server端的密码认证文件
mkdir -p /etc/rsyncd/
echo "bk_password" > /etc/rsyncd/rsync.passwd
chmod 600 /etc/rsyncd/rsync.passwd
  • 执行如下命令初始同步 /opt/test 目录
rsync -avzr --delete --progress --password-file=/etc/rsyncd/rsync.passwd /opt/dockerServiceLog backup@192.168.1.102::test   

inotify 安装

  • 查看是否支持inotify
ll /proc/sys/fs/inotify/

-rw-r--r--. 1 root root 0 May  9 11:46 max_queued_events
-rw-r--r--. 1 root root 0 May  9 11:46 max_user_instances
-rw-r--r--. 1 root root 0 May  9 11:46 max_user_watches

有这几个文件表示支持
  • 编译安装
wget https://github.com/inotify-tools/inotify-tools/releases/download/3.20.2.2/inotify-tools-3.20.2.2.tar.gz
tar xzvf inotify-tools-3.20.2.2.tar.gz
cd inotify-tools-3.20.2.2
./configure --prefix=/usr/local/inotify
make && make install
  • 编写监控文件变化脚本
vi /etc/rsyncd/watchdir.sh
#!/bin/bash
#filename watchdir.sh
path=$1
mkdir -p /var/log/rsync/

/usr/local/inotify/bin/inotifywait -mrq --timefmt '%d/%m/%y/%H:%M' --format '%T %w %f' -e modify,delete,create,attrib $path | while read files
do
    rsync -avzr --delete --progress --password-file=/etc/rsyncd/rsync.passwd $path backup@192.168.1.102::test  
    echo "${files} was rsynced" >>/var/log/rsync/rsync.log 2>&1
done
  • 设置为开机启动脚本
chmod +x /etc/rsyncd/watchdir.sh
echo "" >> /etc/rc.d/rc.local
echo "nohup bash /etc/rsyncd/watchdir.sh /opt/test/ &" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local