If you are using MongoDB and need a Master/Slave configuration that will give you a Slave that will automatically be promoted to Master in the event of a Master DB failure, then MongoDB Replica Pairs will do the job for you. In a Replica Pair the Slave checks the Master for updates every few seconds. If the Master fails to respond, the Slave automatically takes over as the Master. So as far as your application is concerned, everything is still functioning correctly. In the event that the failed pair comes back online, it will see the other pair is currently the Master, will start as a Slave and sync up with the Master.
Testing the Replica Pair setup, it works very well. However, we wanted to be able to run Replica Pairs with MongoDB auth mode turned on so we could password protect our databases. We figured out how to do this setup, after a couple of attempts, so here are our instructions. Hopefully this will help!
Replica Pair using auth mode
Server1 = Your server that has all of the data you want to use
Server2 = Your server that current has no data (This is our Failover server)
Assuming both servers have a data file location of /data/db
- Server1: delete all files with local.*
- rm -f /data/db/local.*
- Server2: ensure your /data/db folder is empty
- Start Server1
- mongod –pairwith Server2 –dbpath /data/db
- Server1 will become the current Master
- Start Server2
- mongod –pairwith Server1 –dbpath /data/db
- Server2 will become the current Slave
- With the mongo shell connect to Server1
- mongo –host Server1
- Add credentials to the admin database
- use admin
- db.addUser(“admin”,”adminpassword”)
- db.auth(“admin”,”adminpassword”)
- Add replication credentials to the admin database
- use local
- db.addUser(“repl”,”replpassword”)
- exit
- Stop Server1 (ctrl+c)
- Server2 should now switch to being the new Master
- With the mongo shell connect to Server2
- mongo –host Server2
- Authenticate with the admin credentials, they were copied from Server1(Master) to Server2 (Slave)
- use admin
- db.auth(“admin”,”adminpassword”)
- Add the replication credentials to the “local” database, these were not copied from Server1 to Server2 automatically while running as replica pairs
- use local
- db.addUser(“repl”,”replpassword”)
- exit
- Stop Server2 (ctrl+c)
- Start Server1 in auth mode (It will be the Master)
- mongod –pairwith Server2 –auth –dbpath /data/db
- Start Server2 in auth mode (It will be the Slave)
- mongod –pairwith Server1 –auth –dbpath /data/db
Python Replica Pair Connection
Example connection string for Python connecting to a replica pair (Server1, Server2)
import pymongo connection=pymongo.Connection.from_uri("mongodb://username:password@Server1,Server2/database")