Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 多伺服器目錄即時同步:Rsync + Sersync 實現雙向自動同步與刪除傳播

編輯:Linux 系統常見問題解答

架構說明

  • Code 伺服器(發布端):10.80.11.245,源碼目錄 /var/www/html。
  • Web 伺服器群(接收端):Web1 (10.80.11.243)、Web2 (10.80.11.244)。
  • 需求:Code 端新增/修改/刪除檔案,實時同步至所有 Web 節點,保持一致性。

一、接收端(Web 節點)配置 Rsync Daemon

1. 環境檢查

uname -a  # 核心需 ≥ 2.6 支援 inotify
rpm -qa | grep rsync  # 未安裝則 yum -y install rsync

2. 建立 Rsync 配置 /etc/rsyncd.conf

uid = root
gid = root
max connections = 36000
use chroot = no
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
timeout = 300

[tongbu]
path = /var/www/html
list = yes
comment = web sync module
ignore errors = yes
read only = no
hosts allow = 10.80.11.245
hosts deny = *
auth users = backup
secrets file = /etc/rsyncd.secrets

3. 建立認證檔與啟動

useradd backup
passwd backup  # 設定系統密碼(可不同於 rsync 密碼)
echo "backup:123456" > /etc/rsyncd.secrets
chmod 600 /etc/rsyncd.secrets

/usr/bin/rsync --daemon --config=/etc/rsyncd.conf
# 加入 /etc/rc.local 開機自啟

二、發布端(Code 伺服器)配置 Sersync

1. 安裝 Sersync

cd /usr/local
wget https://sersync.googlecode.com/files/sersync2.5RC1_32bit_binary.tar.gz
tar zxvf sersync2.5RC1_32bit_binary.tar.gz
cd GNU-Linux-x86

2. 修改配置 confxml.xml 關鍵區段

<localpath watch="/var/www/html">
  <remote ip="10.80.11.243" name="tongbu"/>
  <remote ip="10.80.11.244" name="tongbu"/>
</localpath>
<rsync>
  <auth start="true" users="backup" passwordfile="/etc/rsync.pas"/>
  <userDefinedPort start="false" port="873"/>
  <timeout start="false" time="100"/>
</rsync>

3. 建立密碼檔並啟動

echo "123456#" > /etc/rsync.pas  # 密碼以 # 結尾
chmod 600 /etc/rsync.pas
./sersync2 -d -r  # 常駐進程模式,-r 先執行一次全量同步
# 加入 /etc/rc.local 開機自啟

三、驗證與維護

  • 在 Code 端 /var/www/html 建立/修改/刪除檔案,觀察 Web 端是否即時同步。
  • 查看日誌:tail -f /var/log/rsyncd.log(Web 端)、tail -f /tmp/rsync_fail_log.sh(發布端失敗重試日誌)。
  • 定時全量校驗:配置 <crontab> 區段定期執行完整同步。

附錄:Rsyncd.conf 關鍵參數速查

參數說明
uid/gid守護進程運行身分
use chrootno 可讀取符號連結外的檔案
max connections最大並發連線數
read onlyno 允許上傳(推送端視角)
auth users虛擬用戶名,非系統用戶
secrets file密碼檔路徑,格式 user:pass
hosts allow/denyIP 白/黑名單

總結

Rsync 提供高效增量傳輸,Sersync 基於 inotify 觸發即時同步,兩者結合構建出低延遲、高可靠的多伺服器檔案同步方案。生產環境建議加入監控告警(如同步延遲、失敗重試次數),確保資料一致性。

Copyright © Windows教程網 All Rights Reserved