Last active
May 15, 2020 07:12
-
-
Save SachinMaharana/96eab33910cc018b2ae004baf50b2fb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
docker pull mongo | |
docker network create mongo-cluster | |
docker run -d \ | |
-p 30001:27017 \ | |
--name mongo1 \ | |
--net mongo-cluster \ | |
mongo mongod --replSet mongo-set | |
docker run -d \ | |
-p 30002:27017 \ | |
--name mongo2 \ | |
--net mongo-cluster \ | |
mongo mongod --replSet mongo-set | |
docker run -d \ | |
-p 30003:27017 \ | |
--name mongo3 \ | |
--net mongo-cluster \ | |
mongo mongod --replSet mongo-set | |
docker exec -it mongo1 mongo | |
db = (new Mongo('localhost:27017')).getDB('test') | |
config = { | |
"_id" : "mongo-set", | |
"members" : [ | |
{ | |
"_id" : 0, | |
"host" : "mongo1:27017" | |
}, | |
{ | |
"_id" : 1, | |
"host" : "mongo2:27017" | |
}, | |
{ | |
"_id" : 2, | |
"host" : "mongo3:27017" | |
} | |
] | |
} | |
rs.initiate(config) | |
mongo-set:PRIMARY> | |
DONE | |
// app.js | |
const mongoose = require("mongoose"); | |
const express = require("express"); | |
const PORT = 8080; | |
const HOST = "0.0.0.0"; | |
let conn_string = | |
"mongodb://localhost:30003,localhost:30002,localhost:30001/test?replicaSet=mongo-set"; | |
mongoose | |
.connect(conn_string, { | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
}) | |
.catch((e) => console.log("Error: ", e)); | |
let db = mongoose.connection; | |
db.on("error", console.error.bind(console, "connection error:")); | |
db.on("connecting", function (d) { | |
console.log("Connecting"); | |
console.log(d); | |
}); | |
db.once("open", function () { | |
console.log("Connected; Open"); | |
const app = express(); | |
app.get("/", (req, res) => { | |
res.send("SachinM"); | |
}); | |
app.listen(PORT, HOST); | |
console.log(`Running on http://${HOST}:${PORT}`); | |
}); | |
node app.js | |
error: MongooseError [MongooseServerSelectionError]: getaddrinfo ENOTFOUND mongo1 | |
FIX | |
--- | |
docker exec -it mongo1 mongo | |
cfg = rs.conf() | |
// IP's of VM instead of IP's of Docker private Ip | |
cfg.members[0].host = "172.19.0.2:27017" | |
rs.reconfig(cfg) | |
cfg.members[1].host = "172.19.0.3:27017" | |
rs.reconfig(cfg) | |
cfg.members[2].host = "172.19.0.4:27017" | |
rs.reconfig(cfg) | |
rs.reconfig(cfg) | |
--- | |
node app.js | |
it works now. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment