mongodb4.0.2 replica set master-slave deployment

Source: Internet
Author: User
Tags auth

Introduced

Replication set (Replica sets) is a master/slave replication mechanism for asynchronous synchronization of the same data, so that multiple machines have more than one copy of the same data, due to the automatic failover and recovery features, When the main library is down and no user intervention is required to automatically switch to the master library on other backup servers, a cluster can support up to 7 servers, and any node can be the primary node. All write operations are distributed to the master node, and read operations can be performed on any node, enabling read-write separation and increased load.

Write in front

Previously used master/salve master-slave architecture, unexpectedly 4.0 version does not support master/salve this way, so learning replica sets record

Replica Sets Architecture

Environment
    • System Centos 7.2
    • mongodb4.0.2
    • 10.90.2.10 , 10.90.2.103
Download the deployment package

Download and Unzip

[[email protected] ~]#wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.0.2.tgz[[email protected] ~]#tar xf mongodb-linux-x86_64-rhel70-4.0.2.tgz -C /root/[[email protected] ~]#mv  mongodb-linux-x86_64-rhel70-4.0.2  mongodb4.0.2
Add MONGODB environment variable
echo 'export PATH=/root/mongodb4.0.2/bin:$PATH'  >>  /etc/profilesource /etc/profile
Create a related directory
[[email protected] ~]#cd mongodb4.0.2[[email protected] mongodb4.0.2]# mkdir data logs # 数据目录和日志目录
Create a new configuration file (two nodes are configured the same)
[[email protected] mongodb4.0.2]# cat mongodb.conf logpath=/root/mongodb4.0.2/logs/mongod.log   # 日志路径logappend=true # 是否日志追加fork=true # 后台启动port=27017 # 端口dbpath=/root/mongodb4.0.2/data # 数据目录pidfilepath=/root/mongodb4.0.2/data/mongod.pid # pidoplogSize=4096   # 设置oplog的大小maxConns=640000 # 最大同时连接数 默认2000directoryperdb=true # 设置每个数据库将被保存在一个单独的目录bind_ip=0.0.0.0 # 监听replSet=rs0
Start the master node
[[email protected] mongodb4.0.2]#./bin/mongod -f mongodb.conf  # 主
Enter the master node and create a new root account
[[email protected] mongodb4.0.2]#mongoMongoDB shell version v4.0.2connecting to: mongodb://127.0.0.1:27017MongoDB server version: 4.0.2> db.createUser({ user: 'root', pwd: 'test123', roles: [ { role:"root", db: "admin" } ] });Successfully added user: {    "user" : "root",    "roles" : [        {            "role" : "root",            "db" : "admin"        }    
Stopping the master node
[[email protected] mongodb4.0.2]#./bin/mongod -f mongodb.conf  # 主
Enable password authentication and KeyFile certificate validation

Upload the energy-rc.key generated on the master node to the slave node and configure the same as the primary node

# 生成keyfiles文件[[email protected] mongodb4.0.2]#openssl rand -base64 756 > energy-rc.key    # 设置只读权限[[email protected] mongodb4.0.2]#chmod 400 energy-rc.key                                   # 配置文件中添加如下[[email protected] mongodb4.0.2]#cat   mongodb.confauth=true #打开认证keyFile=/root/mongodb4.0.2/energy-rc.key  #启用key验证
Start master/Slave node
[[email protected] mongodb4.0.2]#./bin/mongod -f mongodb.conf  # 主[[email protected] mongodb4.0.2]#./bin/mongod -f mongodb.conf # 从
Go to the Master node and add the replica set node
2018-09-05t13:26:02.859+0800 I CONTROL [main] automatically disabling TLS 1.0, to force-enable TLS 1.0 specify--SSLDISAB Ledprotocols ' None ' about-to-fork child process, waiting until server was ready for connections.forked Process:6290child PR Ocess started successfully, parent exiting[[email protected] mongodb4.0.2]#./bin/mongomongodb Shell Version v4.0.2connecting to:mongodb://127.0.0.1:27017mongodb Server version:4.0.2> use adminswitched to DB admin> Db.auth  (' Root ', ' test123 ') 1 # view replica set status > Rs.status () {"OK": 0, "errmsg": "No Replset config has been received", "code" : 94, "codename": "Notyetinitialized"}# define configuration information, add two nodes > var cfg={_id: ' Rs0 ', Members:[{_id:0,host: ' 10.90.2.105:270 },{_id:1,host: ' 10.90.2.103:27017 '}]}# initialize copy set > rs.initiate (CFG) {"OK": 1}# View configuration information rs0:secondary> rs.conf () {"_ ID ":" Rs0 "," Version ": 1," ProtocolVersion ": Numberlong (1)," Writeconcernmajorityjournaldefault ": true," M Embers ": [{" _ID ": 0," host ":" 10.90.2.105:27017 "," arbiteronly ": false," buildindexes ": true, "Hidden": false, "priority": 1, "tags": {}, "slaved Elay ": Numberlong (0)," votes ": 1}, {" _id ": 1," host ":" 10.90.2.103:27 017 "," arbiteronly ": false," buildindexes ": True," hidden ": false," Priorit Y ": 1," tags ": {}," Slavedelay ": Numberlong (0)," votes ": 1}], "settings": {"chainingallowed": True, "heartbeatintervalmillis": +, "heart Beattimeoutsecs ": Ten," Electiontimeoutmillis ": 10000," Catchuptimeoutmillis ":-1," Catchuptakeover Delaymillis ": 30000," Getlasterrormodes ": {}," Getlasterrordefaults ": {" W ": 1," wtimeOut ": 0}," Replicasetid ": ObjectId (" 5b8f65bd5eb3d94f12e22e96 ")}}rs0:secondary> Rs.status () {" Se  T ":" Rs0 "," date ": Isodate (" 2018-09-05t05:13:09.326z ")," MyState ": 2," term ": Numberlong (0)," syncingto ":        "", "Syncsourcehost": "", "Syncsourceid":-1, "Heartbeatintervalmillis": Numberlong (+), "Optimes": { "Lastcommittedoptime": {"ts": Timestamp (0, 0), "T": Numberlong ( -1)}, "Appli  Edoptime ": {" ts ": Timestamp (1536124349, 1)," T ": Numberlong ( -1)}," Durableoptime " : {"TS": Timestamp (1536124349, 1), "T": Numberlong ( -1)}, "Laststablecheckpointti            Mestamp ": Timestamp (0, 0)," members ": [{" _id ": 0," name ":" 10.90.2.105:27017 ", "Health": 1, "state": 2, "statestr": "Secondary", "uptime": 191, "Op               Time ": { "TS": Timestamp (1536124349, 1), "T": Numberlong ( -1)}, "Optimedate": Isodate ("201            8-09-05t05:12:29z ")," syncingto ":" "," Syncsourcehost ":" "," Syncsourceid ":-1,            "InfoMessage": "Could not find member-sync from", "ConfigVersion": 1, "Self": true,            "Lastheartbeatmessage": ""}, {"_id": 1, "name": "10.90.2.103:27017", "Health": 1, "state": 0, "statestr": "STARTUP", "uptime":, "optime ": {" ts ": Timestamp (0, 0)," T ": Numberlong ( -1)}," Optimedurable " : {"TS": Timestamp (0, 0), "T": Numberlong ( -1)}, "Optimedate": ISO  Date ("1970-01-01t00:00:00z"), "Optimedurabledate": Isodate ("1970-01-01t00:00:00z"), "Lastheartbeat" : Isodate ("2018-09-05t05:13:09.261z ")," Lastheartbeatrecv ": Isodate (" 1970-01-01t00:00:00z ")," Pingms ": Numberlong (0), "Lastheartbeatmessage": "", "Syncingto": "", "Syncsourcehost": "", "Syncsource  Id ":-1," InfoMessage ":" "," ConfigVersion ":-2}]," OK ": 1}rs0:secondary>

Now exits the connection reconnect under the main library, the status of the master node becomes primary

[[email protected] Mongodb4.0.2]#./bin/mongod--shutdown-f mongodb.conf # Master [[email protected] mongodb4.0.2 ]#./bin/mongod-f mongodb.conf # Master [[email protected] mongodb4.0.2]#./bin/mongomongodb Shell Version V4.0.2connecting TO:MONGODB://127.0.0.1:27017MONGODB server version:4.0.2# requires authentication to view rs0:secondary> show DBS;    2018-09-05t13:26:33.214+0800 E QUERY [js] error:listdatabases failed:{"operationtime": Timestamp (1536125178, 1), "OK": 0, "errmsg": "Command listdatabases requires authentication", "Code": "codename": "Unauthorized" , "$clusterTime": {"Clustertime": Timestamp (1536125178, 1), "signature": {"hash": Bindat A (0, "iszqmtlefm3uvo+uc8luktg9uym="), "KeyId": Numberlong ("6597607397777211393")}}: [EMAIL PR otected]/mongo/shell/utils.js:25:13[email protected]/mongo/shell/mongo.js:67:1[email protected]/ Mongo/shell/utils.js:876:19[email protected]/mongo/shell/utils.js: 766:15@ (SHELLHELP2): 1:1# authentication rs0:primary> use adminswitched to DB adminrs0:primary> db.auth (' root ', ' test123 ') # As can be seen, the current node is dominated by rs0:primary> db.ismaster ();    {"Hosts": ["10.90.2.105:27017", "10.90.2.103:27017"], "setName": "Rs0", "setversion": 1, "IsMaster": True, "secondary": false, "PRIMARY": "10.90.2.105:27017", "Me": "10.90.2.105:27017", "electi Onid ": ObjectId (" 7fffffff0000000000000001 ")," Lastwrite ": {" OpTime ": {" ts ": Timestamp (153612532 7, 1), "T": Numberlong (1)}, "Lastwritedate": Isodate ("2018-09-05t05:28:47z"), "majority OpTime ": {" ts ": Timestamp (1536125327, 1)," T ": Numberlong (1)}," Majoritywritedate ": Isodate (" 2018-09-05t05:28:47z ")}," Maxbsonobjectsize ": 16777216," maxmessagesizebytes ": 48000000," MaxW Ritebatchsize ": 100000," localtime ": Isodate (" 2018-09-05t05:28:57.348z ")," LogicalsessiontimeoutminutEs ": +," minwireversion ": 0," maxwireversion ": 7," readOnly ": false," OK ": 1," operationtime ": Times            Tamp (1536125327, 1), "$clusterTime": {"Clustertime": Timestamp (1536125327, 1), "signature": {    "Hash": Bindata (0, "dunksvz3dkgjfxniufbvdprjtgg="), "KeyId": Numberlong ("6597607397777211393")} }}

Now that the replica set master-slave state has been established, the next test is whether the data can be synchronized properly

Test synchronization

Insert a piece of data in the Lord

Then, on the slave node, see if it is synchronized

Rs0:secondary> use adminswitched to DB adminrs0:secondary> db.auth (' root ', ' test123 ') 1rs0:secondary> show DBS;    2018-09-05t13:31:49.563+0800 E QUERY [js] error:listdatabases failed:{"operationtime": Timestamp (1536125517, 1), "OK": 0, "errmsg": "Not Master and Slaveok=false", "code": 13435, "codename": "Notmasternoslaveok", "$c Lustertime ": {" Clustertime ": Timestamp (1536125517, 1)," signature ": {" hash ": Bindata (0," KIt Tqeb/e0mzlqvqpjzelwzgrem= ")," KeyId ": Numberlong (" 6597607397777211393 ")}}: [email protected] /mongo/shell/utils.js:25:13[email protected]/mongo/shell/mongo.js:67:1[email protected]/mongo/shell/ utils.js:876:19[email protected]/mongo/shell/utils.js:766:15@ (SHELLHELP2): 1:1# default because secondary is not allowed to read and write, if you do not want to resolve           , the method is as follows:rs0:secondary> Db.getmongo (). Setslaveok (); # you can see the data has been synced rs0:secondary> show Dbs;admin 0.000GBconfig        0.000GBlocal 0.000GBpay     0.000gbrs0:secondary> Db.pay.find (). Count () 1rs0:secondary> Db.pay.find () {"_id": "1"} 

Replica sets can also have arbitration node, shard mode, read-write separation, etc., this article will not involve the

mongodb4.0.2 replica set master-slave deployment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.