以gitlab備份數據爲例,經過rsync + inotify實現數據的實時同步。html
源服務器 192.168.1.6 目標服務器 192.168.1.253
yum install -y 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
echo '123456' > /etc/rsync.passwordchmod 600 /etc/rsync.password
源服務器執行,git
echo '111' > /root/1.txtrsync -avz --delete /root/1.txt rsync_git@192.168.1.253::git --password-file=/etc/rsync.password
目標服務器查看,vim
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
同步成功。bash
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
目標服務器查看,ide
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/
下。gitlab