AWS Lambda connecting DocumentDb instance got MongoServerSelectionError: getaddrinfo EAI_AGAIN - node.js

Got following error logs when trying to connecting lambda to documentdb.
TART RequestId: 0946e4e9-9364-4af2-9802-7ea2d8b946d5 Version: $LATEST
2021-08-18T16:25:11.958Z 0946e4e9-9364-4af2-9802-7ea2d8b946d5 INFO insideHandler
2021-08-18T16:25:42.296Z 0946e4e9-9364-4af2-9802-7ea2d8b946d5 ERROR MongoServerSelectionError: getaddrinfo EAI_AGAIN sample-dev-01-instance1.abcde.us-east-1.docdb.amazonaws.com
at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/sdam/topology.js:325:38)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'sample-dev-01-instance1.abcde.us-east-1.docdb.amazonaws.com:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
the VPC of lambda is the same as documentdb instance. The nodejs code connects the instance successfully when running in local but has the issue in lambda.
const { MongoClient } = require('mongodb');
exports.handler = async(event, context) => {
console.log("insideHandler");
const uri = 'mongodb://username:password#sample-dev-01-instance1.abcde.us-east-1.docdb.amazonaws.com:27017';
const client = new MongoClient(uri, {
useNewUrlParser: true,
ssl: true,
tlsCAFile: `rds-combined-ca-bundle.pem`, //Specify the DocDB; cert
retryWrites: false
});
try {
await client.connect();
console.log("connect successfully");
return {
statusCode: 200,
body: JSON.stringify({ message: 'connect successfully' })
}
}
catch (e) {
console.error(e);
}
};
enter code here

EAI_AGAIN is a DNS lookup timed out error, means it is a network connectivity error or proxy related error. Can you confirm whether the Lambda function is using the same security group as the DocumentDB cluster?

Related

I'm getting a timeout error and topology error what to do?

i want to start a local database using mongodb. so I started creating a database using native nodejs driver. but when i run the server then there is a problem that exits. please guide me. thank you
Connection code:
const { MongoClient } = require('mongodb'); // Connection URI
const uri = 'mongodb://localhost:27017/'; // Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect(); // Establish and verify connection
await client.db('fruitsDB').command({ ping: 1 });
console.log('Connected successfully to server');
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\mskga\Desktop\fruitsproject\node_modules\mongodb\lib\sdam\topology.js:284:38)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7) { reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null }, code: undefined, [Symbol(errorLabels)]: Set(0) {} }
this is the error that I'm getting so please tell me what is the error exactly and how to rectify it
Change the host value from localhost to 127.0.0.1.
const uri = 'mongodb://127.0.0.1:27017

Connect SQL Server with Next.js

I am having a problem (ConnectionError) while trying to connect Next.js with SQL Server with mssql, I have enabled TCP/IP, and SQL Server Browser is running.
this is my code:
// db.js
import sql from 'mssql'
// connection configs
const config = {
user: 'test',
password: '1000',
server: '.\sqlexpress',
database: 'DATABASE_NAME',
port: 1433,
options: {
instancename: 'SQLEXPRESS',
trustedconnection: true,
trustServerCertificate: true
},
}
export default async function ExcuteQuery(query, options) {
try {
let pool = await sql.connect(config);
let products = await pool.request().query(query);
return products.recordsets;
}
catch (error) {
console.log(error);
}
}
// api/hello.js
import ExcuteQuery from '../../utils/db';
export default async function handler(req, res) {
console.log(await ExcuteQuery('select * from tbl_category'));
res.status(200).json({})
}
this is the error:
ConnectionError: getaddrinfo ENOTFOUND .
at E:\0 - WEB\pos\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (E:\0 - WEB\pos\node_modules\tedious\lib\connection.js:1012:9)
at Object.onceWrapper (node:events:628:26)
at Connection.emit (node:events:513:28)
at Connection.emit (E:\0 - WEB\pos\node_modules\tedious\lib\connection.js:1040:18)
at E:\0 - WEB\pos\node_modules\tedious\lib\connection.js:1081:16
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
code: 'EINSTLOOKUP',
originalError: ConnectionError: getaddrinfo ENOTFOUND .
at E:\0 - WEB\pos\node_modules\tedious\lib\connection.js:1081:32
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
code: 'EINSTLOOKUP',
isTransient: undefined
}
}
also these are the settings changed:
I tried setting the server to MY_DESKTOP_NAME\SQLEXPRESS but it didn't work, but after disabling and reenabling all the settings it works now, it was kinda like a glitch in the system

Connecting to Azure CosmosDB (MongoDB APIs) from Node Server hosted inside AKS fails

I have Azure CosmosDB account with MongoDB APIs enabled, i'm trying to connect from Node Server deployed with 3 replicas (3 Pods) inside Azure Kubernetes.
Only one POD managed to connect to CosmosDB and the other Pods fails, the error is persistent and nothing in CosmosDB is configured to cause this issue.
Note that same issue happened with another Java application so it's not the Node Server i believe.
The Exception When NodeJS Try to Connect:
MongoServerSelectionError: getaddrinfo EAI_AGAIN abc.mongo.cosmos.azure.com
at Timeout._onTimeout (/app/node_modules/mongodb/lib/sdam/topology.js:312:38)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map {
'abc.mongo.cosmos.azure.com:10255' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'globaldb',
logicalSessionTimeoutMinutes: undefined
}
}
The code:
export const connectToDB = async () => {
const connectionString: string = process.env.CONNECTION_STRING;
try {
const mongoClient = new MongoClient(connectionString);
mongoClient
.connect()
.then(() => {
console.log("Connected successfully to server");
return Promise.resolve();
})
.catch((error: any) => {
console.log("failed to connect to mongodb!");
console.log(error);
});
} catch (error: any) {
console.log(error);
}
};
The error EAI_AGAIN indicates it's a DNS related timeout.
You could bash into one of the pods and dig abc.mongo.cosmos.azure.com to check whether it has a valid DNS configuration.
DNS in Kubernetes can be a little bit error prone, this guide has an excellent walkthrough how they investigated it and they ended up using NodeLocal DNSCache
Also restarting the Code DNS Pods sometimes helps and having your overall cluster in a good state.
See also:
What's the cause of the error 'getaddrinfo EAI_AGAIN'?

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27107

I am currently testing out MongoDB(4.4) Drivers with nodeJS(no mongoose) and trying to connect to localhost:27107. The code below is pretty much copy/paste from the official documentation test code. MongoDB is nicely running in the back.
However, on my command line I get error messages seen as below. Could anyone help me with solving this?
error message:
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27107
at Timeout._onTimeout (/Users/miya/Desktop/FruitsProject/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7) { reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) { 'localhost:27107' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null } }
My code in app.js looks like this;
const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"mongodb://localhost:27107";
// Create a new MongoClient
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
const dbName = "fruitDB";
Thanks in advance!
this thing happens most of the time may be there is Ip restriction issues or anyother to resolve this issue there are two ways
use mongoose instead of mongodb lib
here is the code for connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
2)if you are using atlas then use the connection string for 2 or lower nodejs version

Connection error between nodejs and mongodb atlas using mongoose

I am trying to build a backend app using mongodb atlas. I have followed the instruction but I got error like this
{ MongooseServerSelectionError: connect ECONNREFUSED 18.140.224.177:27017
at new MongooseServerSelectionError
...
message: 'connect ECONNREFUSED 18.140.224.177:27017',
name: 'MongooseServerSelectionError',
reason:
TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers:
Map {
'database-shard-00-01-ayo9w.mongodb.net:27017' => [ServerDescription],
'database-shard-00-00-ayo9w.mongodb.net:27017' => [ServerDescription],
'database-shard-00-02-ayo9w.mongodb.net:27017' => [ServerDescription]
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null },
[Symbol(mongoErrorContextSymbol)]: {} }
and here is my code
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://thanh:Abcdefghijk#database-ayo9w.mongodb.net/test?retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true, },
).then(() => console.log('Connected to database')).
catch(err => console.log('Error in connection', err));
My whitelist entry in mongodb atlas is 0.0.0.0/0
Change username and password with your database username and password. Check mongoDB Atlas where you have created your database and collections.
The reason for this is the internet connection. I just change my wifi connection and it works. This is the link where I get the answer
Error at connecting to MongoDb Atlas Server
Your network or hosting has port 27017 blocked, that's why you can't access server.
To test if the port is blocked you can try this on terminal on mac/linux
(curl portquiz.net:27017) or on cmd (nc -v portquiz.net 27017)
This should solve your issue.

Resources