三台服务器:
172.16.252.128
172.16.252.129
172.16.252.130
1、下载mongo 4.2
https://www.mongodb.com/try/download/community
[root@localhost ~]# wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.2.14.tgz [root@localhost ~]# tar xvf mongodb-linux-x86_64-rhel70-4.2.14.tgz -C /usr/local/ [root@localhost ~]# mv /usr/local/mongodb-linux-x86_64-rhel70-4.2.14/ /usr/local/mongo [root@localhost ~]# vi ~/.bash_profile 加入 PATH=$PATH:/usr/local/mongo/bin [root@localhost ~]# source ~/.bash_profile
mongo副本集搭建:
创建目录
mkdir -p /data/mongodb/{data,log,security}
vi /etc/mongod.conf 粘贴下内容
storage: dbPath: /data/mongodb/data journal: enabled: true systemLog: quiet: true destination: file logAppend: true path: /data/mongodb/log/mongod.log processManagement: fork: true net: port: 27017 bindIp: 0.0.0.0 replication: replSetName: rs0 #security: # keyFile: /data/mongodb/security/mongodb-keyfile operationProfiling: slowOpThresholdMs: 1000 mode: slowOp
启动数据库
mongod --config /etc/mongod.conf
登录数据库
因为没有密码验证,所以可以直接登录,但副本集还未配置,show dbs命令会报异常。
[root@localhost data]# mongo > show dbs 2021-05-19T10:54:22.315+0800 E QUERY [js] uncaught exception: Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not master and slaveOk=false", "code" : 13435, "codeName" : "NotPrimaryNoSecondaryOk" } : _getErrorWithCode@src/mongo/shell/utils.js:25:13 Mongo.prototype.getDBs/<@src/mongo/shell/mongo.js:147:19 Mongo.prototype.getDBs@src/mongo/shell/mongo.js:99:12 shellHelper.show@src/mongo/shell/utils.js:906:13 shellHelper@src/mongo/shell/utils.js:790:15 @(shellhelp2):1:1 >
然后依次配置启动129,130两个服务器的mongo
登录128服务器mongo数据库,初始化副本集群
rsconf = { _id: "rs0", members: [ { _id: 0, host: "172.16.252.18:27017" }, { _id: 1, host: "172.16.252.18:27017" }, { _id: 2, host: "172.16.252.18:27017" } ] } rs.initiate( rsconf )
进入任意一个其它节点,命令行显示为secondary
rs0:SECONDARY>
集群配置已经正常。
配置身份验证,
连接primary节点数据库
use admin db.createUser({ user: "root", pwd: "root", roles: [ {role: "userAdminAnyDatabase", db:"admin"}, {role: "readWriteAnyDatabase", db: "admin"}, {role:"clusterAdmin", db:"admin"} ] })
操作系统生成key,并拷贝到其它服务器
[root@localhost ~]# openssl rand -base64 512 > /data/mongodb/security/mongodb-keyfile [root@localhost ~]# chmod 400 /data/mongodb/security/mongodb-keyfile 拷贝到129、130服务器。 [root@localhost ~]# scp /data/mongodb/security/mongodb-keyfile root@172.16.252.129:/data/mongodb/security/mongodb-keyfile [root@localhost ~]# scp /data/mongodb/security/mongodb-keyfile root@172.16.252.130:/data/mongodb/security/mongodb-keyfile
杀进程
pkill mongod
vi /etc/mongod.conf ---修改配置文件,取消两行注释
security:
keyFile: /data/mongodb/security/mongodb-keyfile
启动数据库。
[root@localhost ~]# mongod --config /etc/mongod.conf 再次登录时需要验证 rs0:PRIMARY> use admin switched to db admin rs0:PRIMARY> db.auth("root","root")
参考文档:
https://wylu.me/posts/fd4a1d37/
https://docs.mongodb.com/manual/reference/configuration-options/