MongoDB是基于分布式文件存储的数据库,介于关系数据库和非关系数据库之间。MongoDB有三种集群方式:Replica Set / Sharding / Master-Slaver。本篇文章暂定只介绍 Replica Set 方式,如果有多个节点请以此类推或者查看官方文档。OS是CentOS 7_x64 系统。MongoDB版本是 mongodb-linux-x86_64-4.0.1.tgz 。
安装MongoDB集群(Replica Set)
准备三台虚拟机(CentOS 7) 192.168.1.21 , 192.168.1.22 , 192.168.1.23
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.1.tgz
tar xf mongodb-linux-x86_64-4.0.1.tgz -C /usr/local/
cd /usr/local && mv mongodb-linux-x86_64-4.0.1 mongodb
192.168.1.21 主节点 配置文件
mkdir -p /data/mongodb/master
vim /etc/mongodb_master.conf
#master.conf
dbpath=/data/mongodb/master
logpath=/data/mongodb/master.log
pidfilepath=/data/mongodb/master.pid
#keyFile=/data/mongodb/mongodb.key
directoryperdb=true
logappend=true
replSet=Evandb
bind_ip=192.168.1.21
port=27017
#auth=true
oplogSize=100
fork=true
noprealloc=true
maxConns=4000
#启动主节点
/usr/local/mongodb/bin/mongod -f /etc/mongodb_master.conf
192.168.1.22 副本节点 配置文件
mkdir -p /data/mongodb/slave
vim /etc/mongodb_slave.conf
#slave.conf
dbpath=/data/mongodb/slave
logpath=/data/mongodb/slave.log
pidfilepath=/data/mongodb/slave.pid
#keyFile=/data/mongodb/mongodb.key
directoryperdb=true
logappend=true
replSet=Evandb
bind_ip=10.211.55.4
port=27017
#auth=true
oplogSize=100
fork=true
noprealloc=true
maxConns=4000
#启动副本节点
/usr/local/mongodb/bin/mongod -f /etc/mongodb_slave.conf
192.168.1.23 仲裁者 配置文件
mkdir -p /data/mongodb/arbiter
vim /etc/mongodb_arbiter.conf
#arbiter.conf
dbpath=/data/mongodb/arbiter
logpath=/data/mongodb/arbiter.log
pidfilepath=/data/mongodb/arbiter.pid
#keyFile=/data/mongodb/mongodb.key
directoryperdb=true
logappend=true
replSet=Evandb
bind_ip=192.168.1.23
port=27018
#auth=true
oplogSize=100
fork=true
noprealloc=true
maxConns=4000
#启动仲裁者节点
/usr/local/mongodb/bin/mongod -f /etc/mongodb_arbiter.conf
其它说明
#keyFile=/data/mongodb/mongodb.key
#auth=true
keyFile和auth选项要在集群配置好后,并且添加了验证用户后在启用(去掉注释即可)
#参数详解
dbpath:存放数据目录
logpath:日志数据目录
pidfilepath:pid文件
keyFile:节点之间用于验证文件,内容必须保持一致,权限600,仅Replica Set 模式有效
directoryperdb:数据库是否分目录存放
logappend:日志追加方式存放
replSet:Replica Set的名字
bind_ip:mongodb绑定的ip地址
port:端口
auth:是否开启验证
oplogSize:设置oplog的大小(MB)
fork:守护进程运行,创建进程
moprealloc:是否禁用数据文件预分配(往往影响性能)
maxConns:最大连接数,默认2000
集群在主节点进行配置
cfg={ _id:"Evandb", members:[ {_id:0,host:'192.168.1.21:27017',priority:2}, {_id:1,host:'192.168.1.22:27017',priority:1}, {_id:2,host:'192.168.1.23:27018',arbiterOnly:true}] };
rs.initiate(cfg)
rs.status()
cfg名字可选,只要跟mongodb参数不冲突,_id为Replica Set名字,members里面的优先级priority值高的为主节点,对于仲裁点一定要加上arbiterOnly:true,否则主备模式不生效
priority表示优先级别,数值越大,表示是主节点
arbiterOnly:true表示仲裁节点
使集群cfg配置生效rs.initiate(cfg)
查看是否生效rs.status()
“stateStr” : “PRIMARY”表示主节点, “stateStr” : “SECONDARY”表示从节点, “stateStr” : “ARBITER”,表示仲裁节点
添加secondary:rs.add({host: "192.168.1.24:27017", priority: 1 })
添加仲裁点:rs.addArb("192.168.1.25:27019") ---集群中有一个仲裁节点足矣
移除节点:rs.remove({host: "192.168.1.24:27017"})
集群安全认证
openssl rand -base64 745 > /data/mongodb/mongodb.key
chmod 600 /data/mongodb/mongodb.key
scp /data/mongodb/mongodb.key 192.168.1.22:/data/mongodb/
scp /data/mongodb/mongodb.key 192.168.1.23:/data/mongodb/
/usr/local/mongodb/bin/mongo 192.168.1.21
use admin
db.createUser({
user:"admin",
pwd:"Evan123.@",
roles:[{role:"userAdminAnyDatabase",db:"admin"}]
});
db.createUser({
user: "root",
pwd: "EvanMxyz.@",
roles: [ { role: "root", db: "admin" } ]
});
db.grantRolesToUser("admin", ["clusterAdmin"])
#取消注释开启认证配置示例
vim /etc/mongodb_master.conf
#master.conf
dbpath=/data/mongodb/master
logpath=/data/mongodb/master.log
pidfilepath=/data/mongodb/master.pid
keyFile=/data/mongodb/mongodb.key
directoryperdb=true
logappend=true
replSet=Evandb
bind_ip=192.168.1.21
port=27017
auth=true
oplogSize=100
fork=true
noprealloc=true
maxConns=4000
#验证认证
/usr/local/mongodb/bin/mongo 192.168.1.21
MongoDB shell version v4.0.1
connecting to: mongodb://192.168.1.21:27017/test
MongoDB server version: 4.0.1
Evandb:PRIMARY> use admin
switched to db admin
Evandb:PRIMARY> db.auth('admin','Evan123.@')
1
Evandb:PRIMARY>
常用命令
#新建库
Evandb:PRIMARY> use Evan
switched to db Evan
Evandb:PRIMARY> db
Evan
Evandb:PRIMARY> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
#未显示刚刚创建的库,需要插入一条数据
#先创建用户
Evandb:PRIMARY> db.createUser({
... user:"Evan",
... pwd:"Evan123.xyz",
... roles:[{role:"readWrite",db:"Evan"}]
... });
Successfully added user: {
"user" : "Evan",
"roles" : [
{
"role" : "readWrite",
"db" : "Evan"
}
]
}
Evandb:PRIMARY> db.auth("Evan","Evan123.xyz")
1
Evandb:PRIMARY> db.Evan.insert({"name":"dbEvan"})
WriteCommandError({
"operationTime" : Timestamp(1537499515, 1),
"ok" : 0,
"errmsg" : "too many users are authenticated",
"code" : 13,
"codeName" : "Unauthorized",
"$clusterTime" : {
"clusterTime" : Timestamp(1537499515, 1),
"signature" : {
"hash" : BinData(0,"SKgyQsICQe9DEZCf0q4t7doJ53M="),
"keyId" : NumberLong("6600257027526623233")
}
}
})
# 报错 "errmsg" : "too many users are authenticated", 是因为之前应认证admin用户
退出命令行,再次执行登录命令,直接切换到Evan库认证就OK
# root @ Evan in ~ [11:14:21]
$ /usr/local/mongodb/bin/mongo 192.168.1.21:27017
MongoDB shell version v4.0.1
connecting to: mongodb://192.168.1.21:27017/test
MongoDB server version: 4.0.1
Evandb:PRIMARY> use Evan
switched to db Evan
Evandb:PRIMARY> db.auth("Evan","Evan123.xyz")
1
Evandb:PRIMARY> db.Evan.insert({"name":"dbEvan"})
WriteResult({ "nInserted" : 1 })
Evandb:PRIMARY> show dbs
Evan 0.000GB
# root @ Evan in ~ [11:15:47]
$ /usr/local/mongodb/bin/mongo 192.168.1.21:27017
MongoDB shell version v4.0.1
connecting to: mongodb://192.168.1.21:27017/test
MongoDB server version: 4.0.1
Evandb:PRIMARY> use admin
switched to db admin
Evandb:PRIMARY> db.auth("admin","Evan123.@")
1
Evandb:PRIMARY> show dbs
Evan 0.000GB
admin 0.000GB
config 0.000GB
local 0.000GB
#修改密码
# root @ Evan in ~ [11:17:12]
$ /usr/local/mongodb/bin/mongo 192.168.1.21:27017
MongoDB shell version v4.0.1
connecting to: mongodb://192.168.1.21:27017/test
MongoDB server version: 4.0.1
Evandb:PRIMARY> use admin
switched to db admin
Evandb:PRIMARY> db.auth("admin","Evan123.@")
1
testdb:PRIMARY> db.changeUserPassword("admin","Evan123.@xyz")
testdb:PRIMARY> exit
bye
# root @ Evan in ~ [11:20:45]
$ /usr/local/mongodb/bin/mongo 192.168.1.21:27017
MongoDB shell version v4.0.1
connecting to: mongodb://192.168.1.21:27017/test
MongoDB server version: 4.0.1
Evandb:PRIMARY> use admin
switched to db admin
Evandb:PRIMARY> db.auth("admin","Evan123.@xyz")
1
Evandb:PRIMARY> exit
bye
#查询用户
Evandb:PRIMARY> use admin
switched to db admin
Evandb:PRIMARY> db.auth("admin","Evan123.@xyz")
1
Evandb:PRIMARY> show users
{
"_id" : "admin.admin",
"user" : "admin",
"db" : "admin",
"roles" : [
{
"role" : "clusterAdmin",
"db" : "admin"
},
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
Evandb:PRIMARY> db.system.users.find()
{ "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "V2+g+eRE6fGNaREqoRvjfw==", "storedKey" : "L74EXshSZdIFS48bMYHbAT9GIs4=", "serverKey" : "gB0sdCfYRxoC0mA8OgmhDfFm5bg=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "vwUKM86H7WQ7u5zdnhrg5Emk91Dn2TQlEps6lw==", "storedKey" : "qOMXB6NUbE46Bb5s6/7CuwsrnTgrQlIik516Isa6DRg=", "serverKey" : "YLPf7cTsZaV2DcE/q+WldpyrqKThLevoaBaZ7C51xog=" } }, "roles" : [ { "role" : "clusterAdmin", "db" : "admin" }, { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
{ "_id" : "admin.root", "user" : "root", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "ldA6uBQJDqzUDVOWQdojRQ==", "storedKey" : "Jvjyxo0SVsCKytJHwW4HW8xCIsk=", "serverKey" : "zXLh7D5yAez7+wG2+omspq0kyWA=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "/xtKGDOXVGZB2WHcDG0gUuJv7x7PMN/34Fry6g==", "storedKey" : "W3dUdDxvJbPPkloj8VsRLZrau8CsmXdhZc5SV5Fpihw=", "serverKey" : "/DfNHizRKA+41lG6j9PWU+U7cqFryu57EVZU1l8NvT0=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "Evan.Evan", "user" : "Evan", "db" : "Evan", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "n8N0FgFEHGsoEkkYIh+9yw==", "storedKey" : "2mUvYxUshy4MU+DsdL77J0ORnhA=", "serverKey" : "gZEfohYfg2ZrpusTNnojZY4NhL8=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "zU9fWrOJzzREdo3PiVY2w9zlwPKqwq0pScp3iQ==", "storedKey" : "LU4PCH0d2QxMb/YKjbRncVeY6tZL1JVxqVbZmI/JI0c=", "serverKey" : "d2mHnvPgCe+u+65byssJcaRgINlAYgNUbMh0rxtA7v8=" } }, "roles" : [ { "role" : "readWrite", "db" : "Evan" } ] }
Evandb:PRIMARY> db.system.users.find().pretty()
{
"_id" : "admin.admin",
"user" : "admin",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "V2+g+eRE6fGNaREqoRvjfw==",
"storedKey" : "L74EXshSZdIFS48bMYHbAT9GIs4=",
"serverKey" : "gB0sdCfYRxoC0mA8OgmhDfFm5bg="
},
"SCRAM-SHA-256" : {
"iterationCount" : 15000,
"salt" : "vwUKM86H7WQ7u5zdnhrg5Emk91Dn2TQlEps6lw==",
"storedKey" : "qOMXB6NUbE46Bb5s6/7CuwsrnTgrQlIik516Isa6DRg=",
"serverKey" : "YLPf7cTsZaV2DcE/q+WldpyrqKThLevoaBaZ7C51xog="
}
},
"roles" : [
{
"role" : "clusterAdmin",
"db" : "admin"
},
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "ldA6uBQJDqzUDVOWQdojRQ==",
"storedKey" : "Jvjyxo0SVsCKytJHwW4HW8xCIsk=",
"serverKey" : "zXLh7D5yAez7+wG2+omspq0kyWA="
},
"SCRAM-SHA-256" : {
"iterationCount" : 15000,
"salt" : "/xtKGDOXVGZB2WHcDG0gUuJv7x7PMN/34Fry6g==",
"storedKey" : "W3dUdDxvJbPPkloj8VsRLZrau8CsmXdhZc5SV5Fpihw=",
"serverKey" : "/DfNHizRKA+41lG6j9PWU+U7cqFryu57EVZU1l8NvT0="
}
},
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
{
"_id" : "Evan.Evan",
"user" : "Evan",
"db" : "Evan",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "n8N0FgFEHGsoEkkYIh+9yw==",
"storedKey" : "2mUvYxUshy4MU+DsdL77J0ORnhA=",
"serverKey" : "gZEfohYfg2ZrpusTNnojZY4NhL8="
},
"SCRAM-SHA-256" : {
"iterationCount" : 15000,
"salt" : "zU9fWrOJzzREdo3PiVY2w9zlwPKqwq0pScp3iQ==",
"storedKey" : "LU4PCH0d2QxMb/YKjbRncVeY6tZL1JVxqVbZmI/JI0c=",
"serverKey" : "d2mHnvPgCe+u+65byssJcaRgINlAYgNUbMh0rxtA7v8="
}
},
"roles" : [
{
"role" : "readWrite",
"db" : "Evan"
}
]
}
#查看副本同步状态
Evandb:PRIMARY> db.printSlaveReplicationInfo();
source: 192.168.1.22:27017
syncedTo: Fri Sep 21 2018 11:02:15 GMT+0800 (CST)
0 secs (0 hrs) behind the primary
1. 数据库用户角色:read、readWrite;
2. 数据库管理角色:dbAdmin、dbOwner、userAdmin;
3. 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
4. 备份恢复角色:backup、restore;
5. 所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
6. 超级用户角色:root // 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)
7. 内部角色:__system
read:允许用户读取指定数据库
readWrite:允许用户读写指定数据库
dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
root:只在admin数据库中可用。超级账号,超级权限