Create a key file for authentication in an existing MongoDB cluster.
$ openssl rand -base64 756 > <path-to-keyfile> $ chmod 400 <path-to-keyfile> $ chown mongodb:mongodb <path-to-keyfile>
2. Add security and replication configuration in /etc/mongod.conf file.
$ vim /etc/mongod.conf
security:
keyFile: <path-to-keyfile>
replication:
replSetName: <replicaSetName>
<a href="https://medium.com/media/d560e3290364ee8096219d8184109e0f/href">https://medium.com/media/d560e3290364ee8096219d8184109e0f/href</a>
Refer this link for more details:
Enforce Keyfile Access Control in a Replica Set - MongoDB Manual
3. Restart MongoDB in existing MongoDB cluster.
$ systemctl restart mongod
$ systemctl status mongod
In case of error please refer /var/log/mongodb/mongod.log file and try to fix on the basis of error logs.
4. Login in mongo with admin credentials.
$ mongo -u <username> -p <password> — authenticationDatabase admin
$ use admin
5. Initiate replica set configuration.
$ rs.initiate()
6. Check the status and configuration of the replica set:
$ rs.conf()
$ rs.status()
7. Now, the existing cluster becomes Primary.
Create a Machine with the required specifications in the cloud platform.
SSH in the machine using the command:
$ ssh <Cluster_IP> $ sudo su
3. Install MongoDB in the new machine. For compatibility, The version of MongoDB should be the same as the version in the existing Primary cluster.
These are the Command to install MongoDB in new compute engine. Please change the version of MongoDB based on your requirement:
$ sudo apt-key adv — keyserver hkp://keyserver.ubuntu.com:80 — recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
$ echo “deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
$ sudo apt-get update
$ sudo apt-get install -y mongodb-org
4. Copy same configuration file /etc/mongod.conf and key file <path-to-keyfile> in new machine from existing primary MongoDB cluster.
change the permission of the key file using these commands:
$ chmod 400 <path-to-keyfile>
$ chown mongodb:mongodb <path-to-keyfile>
5. start mongod in new MongoDB cluster.
$ systemctl start mongod
$ systemctl status mongod
In case of error please refer /var/log/mongodb/mongod.log file and try to fix on the basis of error logs.
Login in Primary cluster:
$ mongo -u <username> -p <password> — authenticationDatabase admin $ use admin
2. Add the new machine in Primary MongoDB:
$ rs.add({host: <Cluster_IP:27017>, priority: <priority>, votes: <votes>})
3. Check status and configuration:
$ rs.conf()
$ rs.status()
4. Login in the new machine and verify about replication:
$ mongo -u <username> -p <password>
This machine will become as secondary and start replicating all data.
sample code to verify replica set configuration using JavaScript.
<a href="https://medium.com/media/2757375a31f78f94bb44a81dbc25e908/href">https://medium.com/media/2757375a31f78f94bb44a81dbc25e908/href</a>