0

I am a front-end programmer trying to learn more backend technologies.

I setup a Mongo database on an EC2 server, and I have a lambda function that I'm trying to make connect to my mongo database.

import * as mongoose from "mongoose";

mongoose.Promise = global.Promise;
let isConnected: boolean = false;

export const connectToDatabase = () => {
  if (isConnected) {
    console.log('using existing database connection');
    return Promise.resolve();
  } else {
    console.log('using new database connection', { isConnected });
    console.log(process.env.MONGODB_URL);
    return mongoose.connect(encodeURI(process.env.MONGODB_URL), {
      auth: {
        user: process.env.MONGODB_USER,
        password: process.env.MONGODB_PASSWORD
      }
    }).then(db => {
      isConnected = true;
    });
  }
};

Here is my error log when testing the function:

2018-05-30T20:51:41.977Z    40fb5cd7-644b-11e8-b6d8-f74282cd6db5    using new database connection { isConnected: false }
2018-05-30T20:51:41.978Z    40fb5cd7-644b-11e8-b6d8-f74282cd6db5    mongodb://PRIVATE_IP:27017/myDeck
2018-05-30T20:51:42.041Z    40fb5cd7-644b-11e8-b6d8-f74282cd6db5    (node:1) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [PRIVATE_IP:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND PRIVATE_IP PRIVATE_IP:27017]

This is the address I'm trying to connect to from my function: mongodb://PRIVATE_IP:27017/myDeck

The EC2-server are on the same VPC and I create an inbound rule on my EC2 security group.

  • An idea: it could be that Lambda doesn't have permission to connect to the EC2 service, even if you've allowed the port in the security group. Just a theory that may or may not be correct. – Tim May 30 '18 at 22:50
  • [This article](https://aws.amazon.com/blogs/security/how-to-create-an-aws-iam-policy-to-grant-aws-lambda-access-to-an-amazon-dynamodb-table/) may have some ideas. – Tim May 31 '18 at 01:27

1 Answers1

0

I found the answer to my question, my mongodb server was starting with the bind_ip equal to localhost, and therefore not able to receiving the connection from the lambda.

I used bind_ip_all for the purpose of testing and it worked fine.