版本:4.0.5
单机1主1从
下载解压,复制一份做从节点
#mongodb_27017配置文件
vi /home/mongodb_4.0.5/mongodb.conf
systemLog:
destination: file
logAppend: true
path: /home/mongodb_4.0.5/logs/mongod.log
storage:
dbPath: /home/mongodb_4.0.5/data
journal:
enabled: true
processManagement:
fork: true # 后台启动fork and run in background
pidFilePath: /home/mongodb_4.0.5/logs/mongod.pid # location of pidfile
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0 # Listen to local interface only, comment to listen on all interfaces.
security:
authorization: enabled
clusterAuthMode: keyFile
keyFile: /home/mongodb_4.0.5/keyfile
replication:
replSetName: mymongodb
#mongodb_27018配置文件
vi /home/mongodb_rs_4.0.5/mongodb_rs.conf
systemLog:
destination: file
logAppend: true
path: /home/mongodb_rs_4.0.5/logs/mongod.log
storage:
dbPath: /home/mongodb_rs_4.0.5/data
journal:
enabled: true
processManagement:
fork: true # 后台启动fork and run in background
pidFilePath: /home/mongodb_rs_4.0.5/logs/mongod.pid # location of pidfile
# network interfaces
net:
port: 27018
bindIp: 0.0.0.0 # Listen to local interface only, comment to listen on all interfaces.
security:
authorization: enabled
clusterAuthMode: keyFile
keyFile: /home/mongodb_rs_4.0.5/keyfile
replication:
replSetName: mymongodb
#生成keyfilea密钥文件
openssl rand -base64 741 >keyfile
#keyfile文件授权不能太高,否则启动报错
chmod 600 keyfile
#2个服务各有一份相同keyfile文件
cp mongodb_4.0.5/keyfile mongodb_rs_4.0.5/
#启动服务1
nohup /home/mongodb_4.0.5/bin/mongod --config /home/mongodb_4.0.5/mongodb.conf &
#启动服务2
nohup /home/mongodb_rs_4.0.5/bin/mongod --config /home/mongodb_rs_4.0.5/mongodb_rs.conf &
#localhost连接进行配置
/home/mongodb_4.0.5/bin/mongo localhost:27017
#集群配置
conf=
{
"_id" : "mymongodb",
"members" : [
{ "_id" : 0, "host" : "192.168.86.1:27017" },
{ "_id" : 1, "host" : "192.168.86.1:27018" }
]
}
rs.initiate(conf)
#查看是否成功:
rs.status()
#新建用户,注意,建立用户后不能再使用localhost连接
admin = db.getSiblingDB("admin")
admin.createUser(
{
user: "admin",
pwd: "admin",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
#注册用户到数据库
db.getSiblingDB("admin").auth("admin", "admin")
#建立集群用户,可以后续管理集群副本集
db.getSiblingDB("admin").createUser(
{
"user" : "cluster",
"pwd" : "cluster",
roles: [ { "role" : "clusterAdmin", "db" : "admin" } ]
}
)
#使用用户连接
/home/mongodb_4.0.5/bin/mongo 192.168.86.1:27017 -u admin -p admin --authenticationDatabase admin
show dbs
#用户授权
use admin
db.grantRolesToUser ( "admin", [ { role: "__system", db: "admin" } ] )
#新建一个db测试
use mydbtest;
db.new101.insert({"name":"new"});
#到这里提示正常的话就完事了