Search code examples
node.jsmongodbamazon-web-servicesamazon-ec2aws-lambda

ec2 local mongo db connection issue inside aws lambda function


I'm using local mongodb of aws ec2. I have set the username and password on db to access it. I'm connecting mongodb on ec2 using nodejs and it works fine. here how i connect.

const mongoose = require('mongoose');
let mongoUri = "mongodb://<username>:<password>@localhost:27017/db_name?authMechanism=DEFAULT&authSource=db_name"
module.exports = function() {
  mongoose
    .connect(mongoUri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useFindAndModify: false,
      useCreateIndex: true,
    })
    .then(() => console.log('Connected to MongoDB...'))
    .catch(error => console.log('Could not connect to MongoDB...', error));
}

and here is how I connect inside aws lambda function

const mongoose = require('mongoose');
module.exports = async function() {
  await mongoose
    .connect('mongodb://<username>:<password>@<ec2_private_ip4_address>:27017/db_name?authMechanism=DEFAULT&authSource=db_name')
    .then(() => console.log('Connected to MongoDB...'))
    .catch(error => console.log('Could not connect to MongoDB...', error));
}

why i used private ipv4 instead of public ipv4?
because it does not connect to mongodb using public ipv4 while with public ipv4 i'm able to make connection on mongo compass and other mongo clients but not on aws lambda.

problem even after the connection after the connection when i try to run a simple query it times out with following error.

2024-06-07T10:36:20.364Z d8bd2319-e7cb-4c04-93d4-8af6c9b14b11 Task timed out after 3.12 seconds
2024-06-07T10:36:20.364Z d8bd2319-e7cb-4c04-93d4-8af6c9b14b11 Task timed out after 3.12 seconds

please let me know how i can fix it. Thanks


Solution

  • it was timeout issue. I increased the time in Edit Timeout in General configuration of lambda function. I increased default 3 seconds to 10 minutes. In the AWS Management Console:

    lambda function -> configuration -> General configuration -> Edit Timeout
    

    enter image description here

    -credits to @MarkB