创建数据保存目录
mkdir /data/db{1,2,3}
编写配置文件
vi /data/db1/mongod.confsystemLog:destination: filepath: /data/db1/mongod.log # log pathlogAppend: truestorage:dbPath: /data/db1 # data directorynet:bindIp: 0.0.0.0port: 28017 # portreplication:replSetName: rs0processManagement:fork: true
启动实例
mongo -f /data/db1/mongod.confabout to fork child process, waiting until server is ready for connections.forked process: 21519child process started successfully, parent exiting
此时三个实例没有任何关系
连接实例,添加复制集
mongo 127.0.0.1:28017rs.initiate(){"info2" : "no configuration specified. Using a default configuration for the set","me" : "主机名称:28017","ok" : 1}rs0:SECONDARY>(此时回车,切换至主节点)rs0:PRIMARY>
主机名称
$ hostname -f主机名称
添加复制集
rs0:PRIMARY> rs.add("(这里是主机名称):28018"){"ok" : 1,"$clusterTime" : {"clusterTime" : Timestamp(1652324261, 1),"signature" : {"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),"keyId" : NumberLong(0)}},"operationTime" : Timestamp(1652324261, 1)}rs0:PRIMARY>
连接从节点,读从节点
rs0:SECONDARY> db.test.find()Error: error: {"topologyVersion" : {"processId" : ObjectId("627c7585c5c5f19182699497"),"counter" : NumberLong(4)},"operationTime" : Timestamp(1652324419, 1),"ok" : 0,"errmsg" : "not master and slaveOk=false","code" : 13435,"codeName" : "NotPrimaryNoSecondaryOk","$clusterTime" : {"clusterTime" : Timestamp(1652324419, 1),"signature" : {"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),"keyId" : NumberLong(0)}}}rs0:SECONDARY>rs.slaveOk() # 允许从节点读