Build the mongodb replica set
I. What is a replica set
A Replica Set is a cluster of MongoDB instances, consisting of one Primary server and multiple Secondary servers. With Replication, updates of data are pushed from the Primary to other instances, and after a certain delay, each MongoDB instance maintains the same copy of the data set. By maintaining redundant database copies, remote data backup, read/write separation and automatic failover can be realized. Earlier versions of MongoDB used master-slave, similar to MySQL, but slave is read-only in this architecture. When the master library goes down, the slave library cannot automatically switch to the master library. The master-slave mode has been replaced with a replica set. In this mode, there is a primary and multiple secondary, and it is read-only. You can assign weights to them. When the master breaks down, the slave with the highest weight switches to the master. In this architecture, you can also establish a role of arbiter, which is only responsible for adjudicating, but not storing data. In this architecture, data is read and written on the master. To achieve load balancing, you need to manually specify the target server of the read library. The above quotations from (blog.51cto.com/zero01/2059…
Two. Start building
The purpose of replica set is to realize the continuous provision of services and remote safe backup of data. Generally, each instance node is stored on a server node. There are not so many servers, so instances are built on the same server and created using different ports.
1. Run three commands in sequence
```
mongod --dbpath=/home/mongodb/db/testReplPrim --logpath=/home/mongodb/logs/mongolog_testReplPrim --logappend --fork --port=27017 --replSet=testRepl
```
```
mongod --dbpath=/home/mongodb/db/testReplSec1 --logpath=/home/mongodb/logs/mongolog_testReplSec1 --logappend --fork --port=27018 --replSet=testRepl
```
```
mongod --dbpath=/home/mongodb/db/testReplSec2 --logpath=/home/mongodb/logs/mongolog_testReplSec2 --logappend --fork --port=27019 --replSet=testRepl
```
Copy the code
2. Select a mongodb instance as the primary node (27017)
Connect to the instance
```
mongo --port 27017
```
```
use admin
```
Copy the code
3. Create a user under admin
```
db.createUser({
user:"test01",
pwd:"abc123",
roles:[{
role:"userAdminAnyDatabase",db:"admin"
},{
role:"clusterAdmin",db:"admin"
}]})
```
```
db.auth('test01','abc123')
```
Copy the code
4. Initialize the replica set
` ` ` Rs. Initiate ({" _id ":" testRepl "and" members ": [{" _id" : 0, "the host" : "10.10.10.10:27017", priority: 3}, {" _id ": 1," the host ":" 10.10.10.10:27 018 ", priority: 2}, {2, "_id" : "the host" : "10.10.10.10:27019", priority: 0, slaveDelay: 86400}]}) ` ` ` IP is random, at that moment, we have to initialize the mongo copy sets, 27017 is the primary node, 27018 and 27019 are secondary nodes. 20179 instance will delay data synchronization by 60 seconds.Copy the code
5. Create a database
```use testdb```
Copy the code
6. Create a user
```db.createUser({"user":"testdb01","pwd":"abc123",roles:[{role:"readWrite",db:"testdb"}]})```
Copy the code
7. Add a New Customers collection and a document
Db.customers. Insert ({"name":"wang"}) at this point, there will be a document in the Customer collection under testdb in instance 27017, and the same data in the other two instancesCopy the code
8. Connect instance 27018
```mongo --port 27018```
```use testdb```
```show collections```
Copy the code
9. It will display:
2018-11-08T16:50:10.122+0800 E QUERY [thread1] Error: listCollections failed: {" OK ": 0, "errmsg" : "not master and slaveOk=false", "code" : 13435 } : _getErrorWithCode@src/mongo/shell/utils.js:25:13 DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:773:1 DB.prototype.getCollectionInfos@src/mongo/shell/db.js:785:19 DB.prototype.getCollectionNames@src/mongo/shell/db.js:796:16 shellHelper.show@src/mongo/shell/utils.js:753:9 ShellHelper @ SRC/mongo/shell/utils. Js: 650:15 @ (shellhelp2) : 1:1 ` ` ` because we are in the secondary node, Need to perform the following commands ` ` ` rs. SlaveOk () ` ` ` ` ` ` show collections ` ` `Copy the code
10. The secondary node has already synchronized the data from the database. Now we have completed the basic replica set, but obviously we did not add the –auth option when we started the database instance. This is not possible in a production environment, so we need to add the –auth option, so let’s close the three service instances first
``` mongod --dbpath=/home/mongodb/db/testReplPrim --logpath=/home/mongodb/logs/mongolog_testReplPrim --logappend --fork --port=27017 --replSet=testRepl --shutdown ``` ``` mongod --dbpath=/home/mongodb/db/testReplSec1 --logpath=/home/mongodb/logs/mongolog_testReplSec1 --logappend --fork --port=27018 --replSet=testRepl --shutdown ``` ``` mongod --dbpath=/home/mongodb/db/testReplSec2 --logpath=/home/mongodb/logs/mongolog_testReplSec2 --logappend --fork --port=27019 --replSet=testRepl --shutdown ```Copy the code
11. Then start each of the three instances
```
mongod --dbpath=/home/mongodb/db/testReplPrim --logpath=/home/mongodb/logs/mongolog_testReplPrim --logappend --fork --port=27017 --replSet=testRepl --auth
```
```
mongod --dbpath=/home/mongodb/db/testReplSec1 --logpath=/home/mongodb/logs/mongolog_testReplSec1 --logappend --fork --port=27018 --replSet=testRepl --auth
```
```
mongod --dbpath=/home/mongodb/db/testReplSec2 --logpath=/home/mongodb/logs/mongolog_testReplSec2 --logappend --fork --port=27019 --replSet=testRepl
--auth
```
Copy the code
12. Connect the primary instance node
` ` ` mongo - port 27017 ` ` ` ` ` ` use admin ` ` ` ` ` ` db. The auth (' test01 ', 'abc123') ` ` ` ` ` ` rs. The status () ` ` ` will see the following status ` ` ` {" set ": "TestRepl ", "date" : ISODate(" 2018-11-08T10:36:32.750z "), "myState" :3, "term" : NumberLong(6), "heartbeatIntervalMillis" : NumberLong(2000), "members" : [ { "_id" : 0, "name" : "RECOVERING", "health" : 1, "state" : 3, "stateStr" : "RECOVERING", "uptime" : 1002, "optime" : {" TS ": Timestamp(1541671316, 2), "t" : NumberLong(6) }, "optimeDate" : ISODate("2018-11-08T10:01:56Z"), "infoMessage" : "could not find member to sync from", "configVersion" : 1, "self" : true }, { "_id" : 1, "name" : "10.10.10.10:25232", "health" : 0, "state" : 6, "stateStr" : "(not reachable/healthy)", "upTime" : 0, "opTime" : { "ts" : Timestamp(0, 0), "t" : NumberLong(-1) }, "optimeDate" : ISODate("1970-01-01T00:00:00Z"), "lastHeartbeat" : ISODate(" 2018-11-08T10:36:30.447z "), "lastHeartbeatRecv" : ISODate("1970-01-01T00:00:00Z"), "pingMs" : NumberLong(0), "authenticated" : false, "configVersion" : -1}, {"_id" :2, "name" : "10.10.10.10:25233", "health" : 0, "state" : 6, "stateStr" : "(not reachable/healthy)", "uptime" : 0, "optime" : { "ts" : Timestamp(0, 0), "t" : NumberLong(-1) }, "optimeDate" : ISODate("1970-01-01T00:00:00Z"), "lastHeartbeat" : ISODate(" 2018-11-08T10:36:30.452z "), "lastHeartbeatRecv" : ISODate("1970-01-01T00:00:00Z"), "pingMs" : NumberLong(0), "authenticated" : false, "configVersion" : -1 } ], "ok" : 1} ' 'indicates that the primary node cannot establish authentication with other nodes. How to establish authentication with other nodesCopy the code
3. Use keyfile access control to establish an authentication mechanism between nodes
1. Generate keyfile
`openssl rand -base64 100 > /usr/local/keyfile/mongodb_keyfile`
Copy the code
2. Modify file permissions
`chmod 600 /usr/local/keyfile/mongodb_keyfile`
Copy the code
3. Copy the generated keyFile file to each node and ensure that the keyfile path is the same as that specified during mongodb startup
4. Shut down the three service instances
`mongod --dbpath=/home/mongodb/db/testReplPrim --logpath=/home/mongodb/logs/mongolog_testReplPrim --logappend --fork --port=27017 --replSet=testRepl --shutdown`
`mongod --dbpath=/home/mongodb/db/testReplSec1 --logpath=/home/mongodb/logs/mongolog_testReplSec1 --logappend --fork --port=27018 --replSet=testRepl --shutdown`
`mongod --dbpath=/home/mongodb/db/testReplSec2 --logpath=/home/mongodb/logs/mongolog_testReplSec2 --logappend --fork --port=27019 --replSet=testRepl --shutdown`
Copy the code
5. Restart three service instances
`mongod --dbpath=/home/mongodb/db/testReplPrim --logpath=/home/mongodb/logs/mongolog_testReplPrim --logappend --fork --port=27017 --replSet=testRepl keyFile=/usr/local/keyfile/mongodb_keyfile --auth`
`mongod --dbpath=/home/mongodb/db/testReplSec1 --logpath=/home/mongodb/logs/mongolog_testReplSec1 --logappend --fork --port=27018 --replSet=testRepl keyFile=/usr/local/keyfile/mongodb_keyfile --auth`
`mongod --dbpath=/home/mongodb/db/testReplSec2 --logpath=/home/mongodb/logs/mongolog_testReplSec2 --logappend --fork --port=27019 --replSet=testRepl keyFile=/usr/local/keyfile/mongodb_keyfile--auth`
Copy the code
6. Example 21071 is used
`mongo --port 27017`
`use admin`
`db.auth('test01','abc123')`
`rs.status()`
Copy the code