第一步、安裝 mongodb 至每台伺服器
準備 3 台以上mongodb伺服器,並在每台上先做以下操作
1、下載mongodb,解壓並移動到 /usr/local/mongodb 目錄
(若未安裝wget,請先 yum install wget 或者 apt-get install wget)
可以在區域網路內某一台web伺服器上下載後,再去從此伺服器下載,會快些。
如:wget -c http://10.0.0.123/mongodb-linux-x86_64-2.6.5.tgz
wget -c https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.5.tgz
tar zxvf mongodb-linux-x86_64-2.6.5.tgz
mv mongodb-linux-x86_64-2.6.5 /usr/local/mongodb
2、建立 mongodb 資料庫(data)、日誌(log) 檔案夾。
mkdir -p /home/mongodb/data /home/mongodb/log
3、設定設定檔:
vi /usr/local/mongodb/mongo.conf
粘貼以下內容到此檔案,:wq 儲存並退出。
systemLog:
destination: "file"
path: "/home/mongodb/log/mongo.log"
logAppend: true
storage:
journal:
enabled: true
dbPath: "/home/mongodb/data"
directoryPerDB: true
processManagement:
fork: true
pidFilePath: "/usr/local/mongodb/mongo.pid"
net:
port: 27017
http:
enabled: true
RESTInterfaceEnabled: true
replication:
replSetName: "REPLICA_NAME_MUST_BE_THE_SAME"
具體的配置參數可參考官方文檔:
http://docs.mongodb.org/manual/reference/configuration-options/
注意空格及縮排
可用的conf檔案
wget http://xclient.info/assets/mongodb/mongo.conf
4、運行 mongodb 進程
/usr/local/mongodb/bin/mongod --config /usr/local/mongodb/mongo.conf
因為要建立資料庫檔案,此處第一次啟動可能會比較慢一點
5、設定開機啟動
vi /etc/rc.d/rc.local
將以下命令粘貼進去,儲存退出
/usr/local/mongodb/bin/mongod --config /usr/local/mongodb/mongo.conf
第一步工作就緒!!!
第二步、設定複本集。
1、在要設定為 主要資料庫 的伺服器上 開啟mongo
/usr/local/mongodb/bin/mongo
2、初始化配置
rs.initiate()
rs.conf()
會看到自己已經成為主節點 ####:PRIMARY> #### 是複本集的名稱
3、新增成員
rs.add("10.0.0.101:27017")
rs.add("10.0.0.102:27017")
……
若要添加 仲裁 節點,命令為:
rs.addArb("10.0.0.111:27017")
註:伺服器數量為偶數的時候,需要添加一個仲裁節點來補充,即複本集的所有伺服器總數必須為奇數。
關於仲裁節點,更多的可以 google
4、設定從資料庫可讀
在每台從伺服器上執行以下即可:
/usr/local/mongodb/bin/mongo
db.getMongo().setSlaveOk()
亦可在主伺服器上使用 /usr/local/mongodb/bin/mongo --host 10.0.0.101 來串連從伺服器進行設定(10.0.0.101 為從伺服器IP)
至此,mongodb 複本集配置完成。
以下為其它一些可能會用到的操作
設定優先權
設定 _ID 為2的伺服器為主伺服器。
cfg = rs.conf()
cfg.members[0].priority = 1
cfg.members[1].priority = 1
cfg.members[2].priority = 2
rs.reconfig(cfg)
設定主伺服器為從伺服器
rs.stepDown()
重設資料庫IP地址
在主伺服器上運行 mongo, 然後執行
cfg = rs.conf()
cfg.members[n].host= 'new_host_name:prot'
rs.reconfig(cfg)
若要重設主伺服器 IP , 則先給主伺服器降級,再在新的主伺服器上執行以上操作。