Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB replica set configuration through js file

Tags:

mongodb

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.

like image 569
prashantas Avatar asked Jul 18 '14 11:07

prashantas


2 Answers

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.

like image 123
Stennie Avatar answered Oct 13 '22 00:10

Stennie


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();
like image 21
Ahmed Samir Avatar answered Oct 13 '22 01:10

Ahmed Samir