MongoDB Replica-set 设置

本文用三个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 local
db.dropDatabase()
exit
service mongodb restart

然后在vm3的mongodb上继续执行rs.add命令:

root@vm3:~# mongo
MongoDB shell version: 2.4.3
connecting to: test
rs1: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:~# mongo
MongoDB shell version: 2.4.3
connecting to: test
rs1: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了。




你可能感兴趣的:(MongoDB Replica-set 设置)