以gitlab备份数据为例,通过rsync + inotify实现数据的实时同步。

源服务器        192.168.1.6

目标服务器      192.168.1.253


目标服务器配置

  • 安装软件:
yum install -y rsync

  • 配置rsync:
vim /etc/rsyncd.conf

uid = root
gid = root
use chroot = no
max connections = 4
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid[git]           #自定义模块名为git
       path = /home/gitlab/data/backups/
       ignore errors       read only = false
       list = true
       hosts allow = 192.168.1.0/24
       auth users = rsync_git
       secrets file = /etc/rsync.password

mkdir -p /home/gitlab/data/backupsecho 'rsync_git:123456' > /etc/rsync.passwordchmod 600 /etc/rsync.password

systemctl enable rsyncd && systemctl start rsyncd


源服务器配置

  • 安装软件:
yum install -y inotify-tools rsync

  • 配置rsync:
echo '123456' > /etc/rsync.passwordchmod 600 /etc/rsync.password

  • rsync同步测试:

源服务器执行,

echo '111' > /root/1.txtrsync -avz --delete /root/1.txt rsync_git@192.168.1.253::git --password-file=/etc/rsync.password

目标服务器查看,

ll /home/gitlab/data/backups/

总用量 4
-rw-r--r-- 1 root root 4 12月 25 16:02 1.txtcat /home/gitlab/data/backups/1.txt

111

同步成功。

  • inotify实时同步脚本:
vim /root/inotify.sh

#!/bin/bash# Defined parameterhost01=192.168.1.253        #inotify-slave的ip地址src=/home/gitlab/data/backups/      #本地监控的目录dst=git     #自定义的rsync服务的模块名user=rsync_git      #rsync服务的虚拟用户rsync_passfile=/etc/rsync.password      #本地调用rsync服务的密码文件inotify_home=/usr/bin       #inotify的安装目录if [ ! -e "$src" ] || [ ! -e "${rsync_passfile}" ] || [ ! -e "${inotify_home}/inotifywait" ] || [ ! -e "/usr/bin/rsync" ]then
    echo "Check File and Folder"fi
    inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' -e modify,delete,create,attrib,move,moved_to $src | while read filesdo
    rsync -avz --delete $src $user@$host01::$dst --password-file=${rsync_passfile} >/dev/null 2>&1done

chmod +x /root/inotify.shnohup bash /root/inotify.sh &

  • 设置脚本自启动:
echo 'nohup /bin/bash /root/inotify.sh &' >> /etc/rc.d/rc.localchmod +x /etc/rc.d/rc.local

  • 实时同步测试:

源服务器执行,

echo 'lzxlzx' > /home/gitlab/data/backups/lzx.txt

目标服务器查看,

ll /home/gitlab/data/backups/

总用量 7
-rw-r--r-- 1 root root          7 12月 25 16:28 lzx.txtcat /home/gitlab/data/backups/lzx.txt

lzxlzx

可以看到,已经实现实时同步。当源服务器/home/gitlab/data/backups/下文件发生变化(增加、删除、内容更改)时,会实时同步文件到目标服务器/home/gitlab/data/backups/下。