Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 站群 rsync 同步架構部署指南(主從推模式)

編輯:Linux 教學

架構圖解

主站 (Source)  ──rsync daemon──►  從站1、從站2、... (Clients)
   │                                    │
   │ 定時任務 (cron/systemd timer)      │ 被動接收
   ▼                                    ▼
/var/www/html  (源碼目錄)          /var/www/html (目標目錄)

一、主站配置 (rsync Server / Sender)

  1. 安裝:yum -y install rsync xinetd (CentOS/RHEL) 或 apt install rsync (Debian/Ubuntu)。
  2. 啟用 xinetd 管理 rsync daemon:
    vim /etc/xinetd.d/rsync
    # 修改 disable = no
    systemctl enable --now xinetd
  3. 編寫 /etc/rsyncd.conf:
    uid = root
    gid = root
    use chroot = yes
    max connections = 200
    timeout = 300
    pid file = /var/run/rsyncd.pid
    lock file = /var/run/rsyncd.lock
    log file = /var/log/rsyncd.log
    
    [site_sync]
        path = /var/www/html
        comment = Web Site Cluster Sync
        read only = yes
        list = yes
        hosts allow = 192.168.1.0/24 10.0.0.0/8
        hosts deny = *
        auth users = rsync_user
        secrets file = /etc/rsyncd.secrets
  4. 建立密碼檔:
    echo "rsync_user:StrongPass123!" > /etc/rsyncd.secrets
    chmod 600 /etc/rsyncd.secrets
  5. 防火牆開放 873 端口:
    firewall-cmd --permanent --add-port=873/tcp
    firewall-cmd --reload

二、從站配置 (Client / Puller)

  1. 安裝 rsync:yum -y install rsync。
  2. 建立密碼檔(僅需密碼,無用戶名):
    echo "StrongPass123!" > /etc/rsync.pass
    chmod 600 /etc/rsync.pass
  3. 測試同步:
    rsync -avz --delete --password-file=/etc/rsync.pass \
      --exclude-from=/etc/rsync_exclude.lst \
      rsync_user@MASTER_IP::site_sync /var/www/html/

    --exclude-from 範例:

    # /etc/rsync_exclude.lst
    *.log
    cache/
    tmp/
    .svn/
    .git/
    *.tmp
  4. 定時同步(每 5 分鐘):
    cat > /etc/cron.d/rsync_site_sync <<'EOF'
    SHELL=/bin/bash
    PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
    */5 * * * * root /usr/bin/rsync -avz --delete --password-file=/etc/rsync.pass --exclude-from=/etc/rsync_exclude.lst rsync_user@MASTER_IP::site_sync /var/www/html/ >> /var/log/rsync_sync.log 2>&1
    EOF

三、關鍵參數解析

四、雙向/多主同步進階(如需)

  • 使用 lsyncd (Lua + inotify) 實現近實時雙向同步。
  • 或部署 GlusterFS/CephFS/DRBD 共享存儲,應用層無感知。
  • 配置檔同步建議採用 Git + CI/CD 或 Ansible 推送,而非 rsync 直接覆蓋生產配置。

五、常見坑點

  1. SELinux 阻擋:setsebool -P rsync_full_access 1 或配置正確 context。
  2. 時區不一致:導致 -t 判斷失效,統一 NTP。
  3. --delete 誤刪:先 --dry-run 驗證,備份關鍵目錄。
  4. 大量小檔案效能差:打包 tar 傳輸或啟用 --checksum 減少 stat 系統調用。

總結

rsync + xinetd + cron 構建的「主推從拉」站群同步架構,成熟、輕量、零依賴。關鍵在於:密碼檔權限 600、排除清單精準、頻寬限制、日誌留存。大規模集群建議引入 lsyncd 或分散式文件系統。

Copyright © Windows教程網 All Rights Reserved
參數作用
-a歸檔模式 = -rlptgoD(遞歸、保留連結/權限/時間/擁有者/設備)
-v詳細輸出
-z傳輸壓縮(跨公網/低帶寬建議開啟)
--delete刪除目標端源端不存在的檔案(鏡像同步)
--exclude-from排除清單檔,每行一個模式
--bwlimit=KBps限制頻寬,避免佔滿業務帶寬
--partial保留斷傳檔案,斷點續傳
--checksum基於校驗和而非時間/大小判斷(慢但精準)