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:
mongo
use admin
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}
]
}
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.
mongo
shellProgrammatically, 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>
.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With