I am running MongoDB server v6.0.4 on AWS EC2 Linux machine, which is publicly accessible.
Using MongoDB: 6.0.4 Using Mongosh: 1.8.0
/etc/mongod.conf
# network interfaces
net:
port: 27017
ipv6: true
bindIp: ::,0.0.0.0 # Tried with public DNS and IP as well here.
security:
authorization: enabled
keyFile: /etc/mongodkeyfile.key
#operationProfiling:
replication:
replSetName: rs0
Able to perform all DB operations by connecting through mongosh on the same machine,
EC2 machine is responding when I ping from my Mac machine.
Whereas when I try connecting through Nodejs application, getting below error
MongoServerSelectionError: getaddrinfo ENOTFOUND ip-xx-x-xx-xxx.ap-south-1.compute.internal
at Timeout._onTimeout (/Users/durgalovababupadala/myprojects/continuum-electrolite/ev-server/node_modules/mongodb/lib/sdam/topology.js:293:38)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7)
And here is my sample code,
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://<user>:<pwd>@<EC2-PublicIP>:27017/<dbname>?replicaSet=rs0&useUnifiedTopology=true";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db('test');
console.log(database);
const myColl = database.collection("pizzas");
const doc = { name: "Neapolitan pizza", shape: "round" };
const result = await myColl.insertOne(doc);
console.log(
`A document was inserted with the _id: ${result.insertedId}`,
);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Thanks in advance,
Update: Executed simple node application with MongoDB connection on Same EC2 machine, and it works.
The error message says getaddrinfo ENOTFOUND ip-xx-x-xx-xxx.ap-south-1.compute.internal
. Note the .internal at the end. If you are not inside the EC2 network, that won't resolve.
When connecting to a replica set, the hostnames and IP addresses in the connection string are the seed list. The driver will attempt to connect to each host in the seed list in turn, and once it gets a connection will run isMaster.
The isMaster command will return the list of member hostname:port in the replica set, as entered in the configuration document. The client then drops the original connection, and connects to the discovered nodes.
In your case, the following happens:
To fix this, rebuild or reconfigure the replica set, ensuring that the valued set for the host
field in each member is a hostname that can be resolve both inside and outside the EC2 network.