A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments. This section introduces replication in MongoDB as well as the components and architecture of replica sets. The section also provides tutorials for common tasks related to replica sets.
If you don’t have Mongo DB this is a good moment to install it. In Debian you can do it:
apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 echo 'deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen' | tee /etc/apt/sources.list.d/mongodb.list apt-get update apt-get install mongodb-org
More information about MongoDB installation here.
I have 3 servers wiht MongoDB with this IPS 192.168.0.[11,12,14].
My intention is make this:
Now you need change 2 lines in mongod.conf
Put real IP:
bind_ip=192.168.0.11 #put here diferent ips
And the name of the replica:
Now start all the servers. I have one on OSX and I want see http stats in port 28017, so It’s needed add –rest when you start MongoDB, sample:
mongod -f mongod.conf --rest
In Debian restart the service:
Ok now we connect to mongo in all servers:
In my case:
mongo 192.168.0.11 mongo 192.168.0.12 mongo 192.168.0.14
Now we’ll create the members:
rs.initiate(); rs.add("192.168.0.12"); rs.add("192.168.0.14); rs.status();
That’s it. We’re done!
You can see rest stats from http://192.168.0.11:28017/_replSet
Two important things:
You’ll obtain this error in secondary members when you try some query:
Run this code:
This allows the current connection to allow read operations to run on secondary members.
How to configure connections? Sample in Mongoose:
mongoose.connect('mongodb://username:password@host:port/database,mongodb://username:password@host:port,mongodb://username:password@host:port?options...' [, options]);
Now it’s time to test. Try to turn off 2 servers and after turn on, turn off primary… It’s nice!