I created 3 containers on docker for mongo:
docker pull mongo
docker network create mongo-cluster
docker run -d -p 27017:27017 --name m1 --net mongo-cluster mongo mongod --replSet mongo-rs
docker run -d -p 27018:27017 --name m2 --net mongo-cluster mongo mongod --replSet mongo-rs
docker run -d -p 27019:27017 --name m3 --net mongo-cluster mongo mongod --replSet mongo-rs
and setup a replica set:
docker exec -it m1 mongo
config = { "_id" : "mongo-rs", "members" : [ { "_id" : 0, "host" : "m1:27017" }, { "_id" : 1, "host" : "m2:27017" }, { "_id" : 2, "host" : "m3:27017" }] }
rs.initiate(config)
mongo-rs:PRIMARY>
> db.pets.insert({name : 'pet'})
WriteResult({ "nInserted" : 1 })
m1 is PRIMARY, m2 and m3 is SECONDARY
After insert a record to m1, I access to m2, m3 and see the recort inserted at m1 appear on m2, m3. It works
But when I try connect to mongodb with NodeJS, use mongoose:
mongoose.connect('mongodb://localhost:27018,localhost:27019,localhost:27020/tsng?replicaSet=mongo-rs', {
autoIndex: false,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 500,
autoReconnect: true,
poolSize: 10,
bufferMaxEntries: 0,
useNewUrlParser: true,
useFindAndModify: false,
})
And an error has been throwed:
failed to connect to server [m3:27017] on first connect [Error: getaddrinfo ENOTFOUND m3
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:69:26) {
name: 'MongoNetworkError'
}]
And one more question, can I have an option to config if I connect to multiple mongodb like above, if one of mongodb is not start up or failed, NodeJS can still working on started mongodb ?