在一台虛擬機裡面安裝了三個mongod實例,一主二從,另外還安裝了一個arbiter。
創建數據總目錄
root@ubuntu:/# mkdir /data/mongodb -p
創建日志目錄
root@ubuntu:/# mkdir /data/mongodb_log -p
創建三個mongod實例的數據目錄
root@ubuntu:/# cd /data/mongodb
root@ubuntu:/data/mongodb# mkdir rs0-0
root@ubuntu:/data/mongodb# mkdir rs0-1
root@ubuntu:/data/mongodb# mkdir rs0-2
啟動三個mongod.
replSet名為 rs0
mongod --port 27020 --dbpath /data/mongodb/rs0-0 --logpath /data/mongodb_log/rs0-0.log --replSet rs0 --logappend &
mongod --port 27021 --dbpath /data/mongodb/rs0-1 --logpath /data/mongodb_log/rs0-1.log --replSet rs0 --logappend &
mongod --port 27022 --dbpath /data/mongodb/rs0-2 --logpath /data/mongodb_log/rs0-2.log --replSet rs0 --logappend &
連接到你想讓其成為主服務器的mongod:
root@ubuntu:/data/mongodb_log# mongo --port 27021
MongoDB shell version: 2.2.4
connecting to: 127.0.0.1:27021/test
>
>
>
> show dbs;
local (empty)
>
初始化replSet
> rs.initiate();
{
"info2" : "no configuration explicitly specified -- making one",
"me" : "ubuntu:27021",
"info" : "Config now saved locally. Should come online in about a minute.",
"ok" : 1
}
獲取配置信息
> rs.conf();
{
"_id" : "rs0",
"version" : 1,
"members" : [
{
"_id" : 0,
"host" : "ubuntu:27021"
}
]
}
獲取replSet的狀態
rs0:PRIMARY> rs.status();
{
"set" : "rs0",
"date" : ISODate("2014-06-30T07:59:09Z"),
"myState" : 1, 表示當前登錄的為主服務器
"members" : [
{
"_id" : 0,
"name" : "ubuntu:27021",
"health" : 1,
"state" : 1, 1表示主服務器
"stateStr" : "PRIMARY",
"uptime" : 132,
"optime" : Timestamp(1404115084000, 1),
"optimeDate" : ISODate("2014-06-30T07:58:04Z"),
"self" : true
}
],
"ok" : 1
}
rs0:PRIMARY>
rs0:PRIMARY>
添加從服務器, localhost不能亂用
rs0:PRIMARY> rs.add("localhost:27021");
{
"errmsg" : "exception: can't use localhost in repl set member names except when using it for all members",
"code" : 13393,
"ok" : 0
}
尼瑪寫錯端口了...
rs0:PRIMARY> rs.add("ubuntu:27021");
{
"errmsg" : "exception: bad replset config -- duplicate hosts in the config object?",
"code" : 13108,
"ok" : 0
}
rs0:PRIMARY> rs.add("ubuntu:27020");
{ "ok" : 1 }
rs0:PRIMARY>
rs0:PRIMARY> rs.add("ubuntu:27022");
{ "ok" : 1 }
rs0:PRIMARY> rs.conf();
{
"_id" : "rs0",
"version" : 3,
"members" : [
{
"_id" : 0,
"host" : "ubuntu:27021"
},
{
"_id" : 1,
"host" : "ubuntu:27020"
},
{
"_id" : 2,
"host" : "ubuntu:27022"
}
]
}
rs0:PRIMARY> rs.status();
{
"set" : "rs0",
"date" : ISODate("2014-06-30T08:01:11Z"),
"myState" : 1,
"members" : [
{
"_id" : 0,
"name" : "ubuntu:27021",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 254,
"optime" : Timestamp(1404115259000, 1),
"optimeDate" : ISODate("2014-06-30T08:00:59Z"),
"self" : true
},
{
"_id" : 1,
"name" : "ubuntu:27020",
"health" : 1,
"state" : 5, 從服務器正在初始化
"stateStr" : "STARTUP2",
"uptime" : 15,
"optime" : Timestamp(0, 0),
"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
"lastHeartbeat" : ISODate("2014-06-30T08:01:10Z"),
"pingMs" : 0,
"errmsg" : "initial sync need a member to be primary or secondary to do our initial sync"
},
{
"_id" : 2,
"name" : "ubuntu:27022",