Mongodb – How to replicate and sync MongoDB localhost to a remote server using replica set

backupmongodbreplication

Initially I started two node(primary and secondary) on same host machine on two different port , secondary was secondary was correctly replicating primary , but my actual requirement is on two different machine with two diff IP address , one should act as Primary other one should act as secondary ,To do that I remove secondary in my local host , and see status below , then tried to add remote IP on same replica , But showing error described below ,

"members" : [
            {
                "_id" : 0,
                "name" : "localhost:27017",
                "health" : 1,
                "state" : 1,
                "stateStr" : "PRIMARY",
                "uptime" : 5359,
                "optime" : {
                    "ts" : Timestamp(1502370582, 1),
                    "t" : NumberLong(1)
                },
                "optimeDate" : ISODate("2017-08-10T13:09:42Z"),
                "electionTime" : Timestamp(1502366671, 1),
                "electionDate" : ISODate("2017-08-10T12:04:31Z"),
                "configVersion" : 4,
                "self" : true
            }
        ],
        "ok" : 1
    }

myreplset:PRIMARY> config = {_id:"myreplset", members:[          {_id:0, host:"localhost:27017"},          {_id:1, host:"192.168.205.59:27017"} ]          };
    {
        "_id" : "myreplset",
        "members" : [
            {
                "_id" : 0,
                "host" : "localhost:27017"
            },
            {
                "_id" : 1,
                "host" : "192.168.205.59:27017"
            }
        ]
    }
    myreplset:PRIMARY> rs.initiate(config);
    {
        "info" : "try querying local.system.replset to see current configuration",
        "ok" : 0,
        "errmsg" : "already initialized",
        "code" : 23,
        "codeName" : "AlreadyInitialized"
    }



myreplset:PRIMARY> rs.add("192.168.205.59:27017"); 
{ "ok" : 0,
 "errmsg" : "Either all host names in a replica set configuration must be localhost references, or none must be; found 1 out of 2", 
"code" : 103, "codeName" : "NewReplicaSetConfigurationIncompatible"
 }

Best Answer

Please use rs.add("host:port") command to add new node to replica set.

The main problem is that you can NOT mix localhost and IP addresses. If one member is on localhost, every member must be on localhost

You can of course use procedure:

var cfg=rs.conf()
cfg.members
<copy that to text editor and make changes>
cfg.members=<paste here edited members section>
rs.reconfig(cfg)