How to setup Mongo Replica Set with Primary, Secondary & Analytical Node — with and without Docker
Things to care of before we start the set up :
- Three standalone mongo db instances — !! make sure we have same MAJOR, MINOR & PATCH version (i was performing with Mongo version 4.2.8)
- To connect all three instance with authentication. we need to have
- a KeyFile for replicaset members to communicate with each other.
- and username and password for you to connect to an instance with authentication. (so before starting a replica set — create an admin user with roles of root and clusterAdmin)
- also use the below command to let mongo use this keyfile (permissions)
chown mongodb:mongodb ./mongokey.key
3. Make sure all servers are accessible
- AWS has external IP, internal IP, public DNS & private DNS — you should you public DNS in this case to ensure reachability and accessibility.
- incase of external server — you can use IP address
- please check from each server if you are able to access the proposed members of the replica set
4. restart all the nodes with replica set option (either in /etc/mongo.conf or command line option — replSet “replicaName”
5. At this stage we will have two options -> a. single stroke replica instantiation or b. stage-wise replica instantiation
a. single-stroke:
b. stage-wise — if you have an existing standalone instance with data and want to convert with lowest possible down time you can use this approach
after all the replica members are in sync then we can use the below to make the set accordingly
Now a full fledged mongo — replica set with Analytical node will be ready
For connecting to Analytical node you need to connect with readPreference option set to secondary preferred as in below command
mongodb://userName:passwrod@<dnshostname>:<customport>/test?authSource=admin&replicaSet=replicaName&readPreference=secondaryPreferred
you should also change the application connection string to utilise the high availability feature that mongo replication provides
IF YOU WANT TO DOCKERIZE THE MONGO CONTAINERS
use the below command to effectively use the mongo containers
things to do before starting docker container :
- make a mongo.conf file for the docker to use
- generate the mongokey (this key should be the same in all the replicSet members)
- sudo chown 999:999 mongodb.key (this is used for inter mongo replica set authentication)
we need the data in docker to be mapped to a local folder so the data will persist between docker container removals and restarts
docker run -d — name containerName -v /folder/mongodb/data/:/data/db -v /folder/mongodb/mongod.conf:/etc/mongo.conf -v /folder/mongodb/mongodb.key:/mongodb.key -p <customport>:27017 mongo:4.2.8 — config /etc/mongo.conf
use the below command in two setps
- first time — with out the security options — to create the user in admin db
- second time use authentication and kefFile as well as replicaset options