复制集节点:
192.168.98.9:27008 192.168.98.9:27007
创建文件夹 mkdir /mongo cd mongo mkdir m1 m2 cd m1 mkdir log conf db cd m2 mkdir log conf db chmod 777 log log 文件夹需要提权 因为mongodb会创建日志文件 cd /m1/conf 创建配置文件 vim mongod.conf
storage:
dbPath: /data/db
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
systemLog:
destination: file
logAppend: true
path: /data/log/mlogs
# where to write logging data.
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0
# how the process runs
security:
#开启认证
authorization: enabled
# 指定keyfile认证
clusterAuthMode: keyFile
keyFile: /data/conf/mongodb.keyfile
#operationProfiling:
replication:
oplogSizeMB: 10240
#复制集名称
replSetName: rs1
配置文件节点之间有所不同 cp mongod.conf /mongo/m2/conf/ openssl rand -base64 736 > /mongo/m1/conf/mongodb.keyfile keyfile文件只生成一次 拷贝到每个节点上使用 chmod 600 mongodb.keyfile docker 环境时需要执行 chown 999 mongodb.keyfile cp mongodb.keyfile /mongo/m2/conf/ 准备工作做好后启动容器 docker run -d -p 27007:27017 --name="m1" -v /mongo/m1:/data -d mongo:4.2.6 --config /data/conf/mongod.conf docker run -d -p 27008:27017 --name="m2" -v /mongo/m2:/data -d mongo:4.2.6 --config /data/conf/mongod.conf 进入容器 docker exec -it m1 bash 进入mongo mongo rs1 是配置文件中的复制集名称 myconf = {"_id":"rs1","members":[{"_id":0,"host":"192.168.98.9:27007"},{"_id":1,"host":"192.168.98.9:27008"}]} rs.initiate(myconf) //初始化配置文件 查看集群状态 rs.status() 在从节点上想查询需要执行 rs.slaveOk() 先创建 admin用户 可以操作admin库并且继续创建其他用户 use admin db.createUser( {user: "admin",pwd: "123456",roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]}) db.auth("admin", "123456") 登录admin用户后继续创建用户 root权限 db.createUser({user:"root",pwd:"123456",roles:["root"]}) 仓库权限 db.createUser( { user: "test", pwd: "test", roles: [ { role: "dbOwner", db: "check" } ] })
出现下面这种情况是因为两个客户端登录用户不一致导致的 统一登录就好
"operationTime" : Timestamp(1591156470, 1),
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { replSetGetStatus: 1.0, lsid: { id: UUID(\"af04026d-c9e9-4cae-a6d3-933f89ce5e28\") }, $clusterTime: { clusterTime: Timestamp(1591156460, 1), signature: { hash: BinData(0, E58BFCE34514E495F96F60E0AFF6F563293BE0B3), keyId: 6833964099525672961 } }, $db: \"admin\" }",
"code" : 13,
"codeName" : "Unauthorized",
"$clusterTime" : {
"clusterTime" : Timestamp(1591156470, 1),
"signature" : {
"hash" : BinData(0,"n+dTy2gBDNlXcY5Gi2qwIZYgjfE="),
"keyId" : NumberLong("6833964099525672961")
成功后可以看见 、 spring boot连接mongodb复制集
uri: mongodb://check:[email protected]:27008,192.168.98.9:27007/check?replSet=rs1