I have a MongoDB which only allow connection from localhost, running on my ec2. Currently, only my nodejs app which runs on the same ec2 instance connects to the mongodb using this command mongoose.connect('mongodb://user:pass@localhost:27017/mydb', {})

Now I'm in the process of migrating my codes to lambda. Since my mongodb only allow localhost connection, currently my lambda won't be able to connect to my mongodb, so I need to open my MongoDB connection to allow connection from external IP right? But I was told by someone (but he's not really sure about it anyway) that I can just use VPC to allow lambda to connect to my MongoDB without needing me to open my MongoDB connection or make any changes to my MongoDB configuration. Is he right on this?

I just started reading about this VPC because I've never used it before, but I'm just asking here for confirmation or any other alternatives.

Thank you


The simple answer is NO, you cannot connect to MongoDB from the outside without enabling remote connections. First, you need to set up MongoDB, edit the /etc/mongod.conf file under Network Interfaces to update the bindIp value to Now you need to create a VPC (if you don't have one), assign the lambda and EC2 to the same VPC, create a security group and assign the lambda and EC2 to that group In your Nodejs connection string, make sure you reference the EC2 private IP.

  • In that case (if cannot connect to MongoDB from outside without enabling remote connections), after I enabled remote connection, why should I use VPC to connect lambda to MongoDB? I can just use direct connection from Lambda to MongoDB no? Or am I missing something? – imin Aug 13 '20 at 16:13
  • The VPC is required for security reasons since Lambda does not have a fixed set of IP addresses that it uses, you should update your AWS firewall to allow inbound traffic to port 27017 of your EC2 instance from anywhere. – Albert Aug 14 '20 at 8:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.