一、配置文件/etc/mongod.conf
[root@mongo01 ~]# egrep -v "^(#|$)" /etc/mongod.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
systemLog:
destination:
file
logAppend:
true
path:
/data/mongodb/log/rs1
.log
storage:
dbPath:
/data/mongodb/data
directoryPerDB:
true
journal:
enabled:
true
processManagement:
fork:
true
# fork and run in background
pidFilePath:
/data/mongodb/conf/mongod
.pid
# location of pidfile
net:
port: 27027
replication:
oplogSizeMB: 50000
replSetName: rs1
|
[root@mongo01 ~]#
[root@mongo01 ~]# ls /data/mongodb/
1
|
arbiter conf data log startaribiter.sh
|
[root@mongo01 ~]# ls /data/mongodb/arbiter/
1
|
arbiter.conf conf data log
|
[root@mongo01 ~]# egrep -v "^(#|$)" /data/mongodb/arbiter/arbiter.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
systemLog:
destination:
file
logAppend:
true
path:
/data/mongodb/arbiter/log/rs1
.log
storage:
dbPath:
/data/mongodb/arbiter/data
directoryPerDB:
true
journal:
enabled:
true
processManagement:
fork:
true
# fork and run in background
pidFilePath:
/data/mongodb/arbiter/conf/mongod
.pid
# location of pidfile
net:
port: 27029
replication:
oplogSizeMB: 50000
replSetName: rs1
|
[root@mongo01 ~]# cat /data/mongodb/startarbiter.sh
1
2
3
4
|
#!/bin/sh
.
/etc/rc
.d
/init
.d
/functions
cd
${0%/*}
/arbiter
daemon --user mongod
"mongod --config arbiter.conf"
|
[root@mongo01 ~]#
注意:arbiter.conf文件的属主、属组为mongod
二、启动服务,配置副本集
service mongod start
/data/mongodb/startaribiter.sh
启动第二个节点
然后:在primary上,
1
2
3
4
|
rs.initiate()
rs.add(
"mongodb2.example.net"
)
rs.add(
"mongodb3.example.net"
)
rs.addArb(“mongodb1.example.net:27029”)
|
如果希望降低primary的优先级:
1
2
3
4
|
cfg = rs.conf()
cfg.members[2].priority = 0.5
rs.reconfig(cfg)
rs.status()
|
实现复制后,在从节点上查看数据如下:
1
2
|
SECONDARY> rs.slaveOk()
SECONDARY> show collections
|
三、 使用keyFile实现复制验证
在主节点上创建群集用户及密码如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
admin = db.getSiblingDB(
"admin"
)
admin.createUser(
{
user: “clusteradmin”,
pwd
: “clusterpwd”,
roles: [
{ role:
"userAdminAnyDatabase"
, db:
"admin"
},
{ role: “clusterAdmin”, db:
"admin"
},
{ role: “root”, db:
"admin"
}
]
}
)
|
测试用户:
1
|
db.getSiblingDB(
"admin"
).auth(“clusteradmin”, “clusterpwd” )
|
在各从节点上关闭服务:
use admin
db.shutdownServer()
包括arbiter节点也要关闭服务,最后再关闭primary节点的服务。
然后在各配置文件mongdb.conf中添加认证文件:
1
2
|
security:
keyFile:
/data/mongodb/conf/keyfile
.key
|
[root@mongo01 ~]# cat /data/mongodb/conf/keyfile.key
1
|
abcdefgh
|
该文件的权限必须是600或400,并把该文件复制到各节点上(保持内容相同),该文件也可以使用以下命令生成:
1
|
openssl rand -base64 755 > path-to-keyfile
|
最后再新启动各节点的mongodb服务,并重新login ,测试。
参考:https://docs.mongodb.com/manual/tutorial/deploy-replica-set/
https://docs.mongodb.com/manual/tutorial/enforce-keyfile-access-control-in-existing-replica-set/