Converting StandAlone MongoDB to Replicaset

Overview

Hi all, today i’ll show you how to convert standalone mongoDB mode to replicaset, in this post im just converting single instance.

Backup MongoDB

Before going further we need to backup all database, just in case s**t happen.

mkdir backup
mongodump --gzip --username adminmongo --password "mymongopassword" --host "localhost:27017" --out ~/backup/mongo/mongo-`date "+%d-%m-%Y"` --authenticationDatabase admin

Converting MongoDB to ReplicaSet

  • Login to mongo shell and shutdown instance.
    mongosh -u adminmongo -p  --authenticationDatabase admin
    use admin
    db.adminCommand(
       {
          shutdown: 1,
          comment: "Convert to cluster"
       }
    )
    • change the configuration mongodb and set replica name like this
    vi /etc/mongod.conf
    ----
    security:
      authorization: enabled
      keyFile: /var/lib/mongodb/mongod.key
      
    replication:
      replSetName: bippo
    • Create keyFile for authentication for each cluster.
    openssl rand -base64 741 > /var/lib/mongod/mongod.key
    chmod 400 /var/lib/mongod/mongod.key
    chown mongod:mongod /var/lib/mongod/mongod.key 
    • Before starting the service we need to edit current systemd configuration mongodDB file , because when i first time implement i got an error.
     'Environment variable MONGODB_CONFIG_OVERRIDE_NOFORK == 1, overriding "processManagement.fork" to false"'.
    vi /lib/systemd/system/mongod.service
    # uncomment this line
    #Environment="MONGODB_CONFIG_OVERRIDE_NOFORK=1"
    • restart systemd and start mongodb
    systemctl daemon-reload
    systemctl start mongod; systemctl status mongod
    • Login to mongodb and initiate replicaset
    mongosh -u adminmongo -p  --authenticationDatabase admin
    > rs.initiate()
    # to verify replicate use this command
    rs.status()
    # to check replicaset configuration
    rs.config()

    Connecting Apps using replicaSet string

    This is an example of configuration client apps connecting to mongo replicaset

    mongodb.uri=mongodb://adminmongo:mymongopassword@172.17.0.1:27017/admin?replicaSet=myReplicaSetName

    Reference Link

    https://www.mongodb.com/docs/manual/tutorial/convert-standalone-to-replica-set