本文用三個MongoDB server來架設replica-set。
首先分別準備三個UBuntu vm, 裡面安裝了MongoDB instance.
然後每個vm的/etc/hosts裡面都包含了另外兩個vm的ip和主機名稱。
這樣確保每個vm都能通過主機名稱串連到其他兩個vm.
我的vm分別是:vm1, vm3, vm4. IP分別是192.168.1.51, 192.168.1.52和192.168.1.53
依次登入所有的vm,然後編輯/etc/mongodb.conf檔案,取消注釋,並設定replSet
replSet = rs1 // 必須設定為一個名字,千萬別不同
添加
fork=true
重新啟動mongodb
service mongodb restart
運行下面的命令:
ssh到vm3,登入到mongodb, 然後執行rs.initiate建立一個replicaset,並用config檢查配置。
> rs.initiate(){"info2" : "no configuration explicitly specified -- making one","me" : "vm3:27017","info" : "Config now saved locally. Should come online in about a minute.","ok" : 1}> rs.config(){"_id" : "rs1","version" : 1,"members" : [{"_id" : 0,"host" : "vm3:27017"}]}
注意,3個vm中只能選中一個運行rs.initiate命令,如果在其他的vm中不小心也運行了。需要用下面的方法清除之:
use localdb.dropDatabase()exitservice mongodb restart
然後在vm3的mongodb上繼續執行rs.add命令:
root@vm3:~# mongoMongoDB shell version: 2.4.3connecting to: testrs1:PRIMARY> rs.add("vm1"){ "errmsg" : "exception: set name does not match the set name host vm1:27017 expects", "code" : 13145, "ok" : 0}rs1:PRIMARY> rs.add("vm4"){ "errmsg" : "exception: set name does not match the set name host vm4:27017 expects", "code" : 13145, "ok" : 0}
報錯的原因很奇怪。查了半天,難道是剛才修改了/etc/hosts沒有重新啟動的原因嗎?
把三個vm都重新啟動,再試!
root@vm3:~# mongoMongoDB shell version: 2.4.3connecting to: testrs1:PRIMARY> rs.add("vm4"){ "ok" : 1 }rs1:PRIMARY> rs.add("vm1"){ "ok" : 1 }
成功了。不容易啊!再看一下配置:
rs1:PRIMARY> rs.config(){"_id" : "rs1","version" : 3,"members" : [{"_id" : 0,"host" : "vm3:27017"},{"_id" : 1,"host" : "vm4:27017"},{"_id" : 2,"host" : "vm1:27017"}]}
來看看狀態:
s1:PRIMARY> rs.status(){"set" : "rs1","date" : ISODate("2013-05-04T12:36:28Z"),"myState" : 1,"members" : [{"_id" : 0,"name" : "vm3:27017","health" : 1,"state" : 1,"stateStr" : "PRIMARY","uptime" : 380,"optime" : {"t" : 1367670744,"i" : 1},"optimeDate" : ISODate("2013-05-04T12:32:24Z"),"self" : true},{"_id" : 1,"name" : "vm4:27017","health" : 1,"state" : 2,"stateStr" : "SECONDARY","uptime" : 248,"optime" : {"t" : 1367670744,"i" : 1},"optimeDate" : ISODate("2013-05-04T12:32:24Z"),"lastHeartbeat" : ISODate("2013-05-04T12:36:28Z"),"lastHeartbeatRecv" : ISODate("1970-01-01T00:00:00Z"),"pingMs" : 0,"syncingTo" : "vm3:27017"},{"_id" : 2,"name" : "vm1:27017","health" : 1,"state" : 2,"stateStr" : "SECONDARY","uptime" : 244,"optime" : {"t" : 1367670744,"i" : 1},"optimeDate" : ISODate("2013-05-04T12:32:24Z"),"lastHeartbeat" : ISODate("2013-05-04T12:36:26Z"),"lastHeartbeatRecv" : ISODate("2013-05-04T12:36:28Z"),"pingMs" : 1,"syncingTo" : "vm3:27017"}],"ok" : 1}
vm3已經被選舉為primary了。