简体   繁体   中英

MongoDB replica set configuration through js file

I have configured a replica set for MongoDB manually.

Once I have launched the daemons on 3 nodes and after they are up and running, from the node which I have identified as "Primary" I run the following command:

  1. mongo

    • This will drop me into the mongo shell
  2. use admin

  3. Create replica set config:

     cfg = { _id: 'csReplicaSet', members: [ { _id: 0, host: 'node1IpAddress:27017'}, { _id: 1, host: 'node2IpAddress:27017'}, { _id: 2, host: 'node3IpAddress:27017', arbiterOnly: true} ] } 
  4. rs.initiate(cfg)

I want to know how can I do these steps in a JavaScript file that will be recognised by mongo. I want to automate these steps.

Passing your init script to the mongo shell

Programmatically, you're almost there. You could save your instructions to a JavaScript file and run this on the mongo command line. You should also capture & print the results of rs.initiate() in case there is an error:

eg. contents of initreplica.js :

var cfg = { _id: 'csReplicaSet',
    members: [
        { _id: 0, host: 'node1IpAddress:27017'},
        { _id: 1, host: 'node2IpAddress:27017'},
        { _id: 2, host: 'node3IpAddress:27017', arbiterOnly: true}
    ]
};

var error = rs.initiate(cfg);
printjson(error);

Run this from the command line with:

 mongo node1IpAddress:27017/admin initreplica.js

Note that this assumes your three mongod nodes have been started on the same IP addresses including --replSet csReplicaSet parameter. You also only need to do this init sequence once unless you are rebuilding the replica set from scratch (and there is no existing replica set config).

I would also recommend reading the section of the manual on Writing Scripts for the mongo shell . It includes some helpful hints such as how to open new connections to other MongoDB servers as well as the JavaScript equivalents of some shell helpers like use <db> .

Automating a production deployment

If you're looking for ways to automate building a production MongoDB cluster, you should look into recipes for configuration management tools like Chef or Puppet. There is also an Automation feature coming soon as part of MMS (MongoDB Management Service); the Automation feature is currently in beta testing.

I Just run it this way

mongo --port 27018 init_replica.set.js

and this is the script for init from the

config = { _id: "m101", members:[
          { _id : 0, host : "MYHOST:27017" ,priority : 0, slaveDelay : 5 },
          { _id : 1, host : "MYHOST:27018"},
          { _id : 2, host : "MYHOST:27019"} ]
};
rs.initiate(config);
rs.status();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM