最近在研究網站負載平衝 (Load Balance) 的技術. 在分載的部份已經獲得一定的進展, 但是如果多個網站伺服器(Apache 2) 之間的檔案同步也是個問題. 資料庫 MySQL 還可以使用一個來提供集中的資料或是用 replication 來達到資料庫同步. 但是在 Apache 下的檔案如果要同步, 就是另一個挑戰.
一般來說如果要同步檔案, 搜尋的結果都是用 rsync. 設定完 rsync 之後, 才發現 rsync 只有單方面的同步. 假設有2台 Apache servers, 只單方從一號同步到二號, 那如果用 Load Balancer 分到二號 server 上做的變更, 就不會再同步到一號上了. 再研究後發現 Unison 可以同步檔案, 再加上 cron job 的設定即可.
1. 安裝 Unison
1 | sudo apt-get install unison |
2. 修改 Unison 預設值
1 | sudo nano /home/username/.unison/default.prf |
* note: username 就是你 Ubuntu 登入的使用名
3. Default.prf 的內容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | # skip asking for confirmations on non-conflicting changes auto=true # the user interface will ask no questions at all batch=true # Unison will request an extra confirmation if it appears that the entire replica has been deleted confirmbigdeletes=true # Unison will use the modification time and length of a file as a `pseudo inode number' when scanning replicas for updates, instead of reading the full cont$ fastcheck=true # the group attributes of the files are synchronized group=true # the owner attributes of the files are synchronized owner=true # prefer newer version of files in case of conflicts prefer=newer # the textual user interface will print nothing at all, except in the case of errors. silent=true # file modification times (but not directory modtimes) are propagated. times=true |
4. 設定完之後, 就要設定免密碼登入到二號機, 首先先設定主機的 ssh 密碼
1 | ssh-keygen -t dsa |
5. 複制一號機的密碼到二號機上
1 | ssh-copy-id -i /home/username/.ssh/id_dsa.pub remoteuser@apache2.remote.com |
6. 完成之後, 就可以不用再打入密碼使用 Unison 了
1 | sudo unison /var/www ssh://remoteuser@apache2.remote.com//var/www |
Note: 如果在測試 unison 時發生permission 權限問題, 請確認 remoteuser 是否有權限對/var/www 目錄做更改. 如果沒有, 就用chgrp 和 chown 來變更
7. 最後再把上一步的指令加入 cron job 裡. 此例是每5分鐘同步一次
1 2 3 | sudo crontab -e */5 * * * * sudo unison /var/www ssh://remoteuser@apache2.remote.com/var/www &> /dev/null |



