user3768533
user3768533

Reputation: 1347

Connecting to Mongodb Amazon EC2 instance programmatically in Nodejs

I am making a NodeJS webapp. I would like to deploy the app using Amazon's elastic beanstalk and I would like to use MongoDB as the database. Right now my understanding of a solution is to:

  1. Set up a MongoDB instance on an Amazon EC2 instance (I've already done this)
  2. Connect to this database programmatically in server.js to read and write to the database

Does this solution make sense? If so, how do I connect to the EC2 MongoDB instance programmatically?

I've found the official MongoDB package for node:https://www.npmjs.com/package/mongodb

but the documentation only mentions connecting to a local instance of MongoDB:

// Connection URL 
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server 
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  db.close();
});

Current I am able to ssh into my EC2 MongoDB instance but I don't understand how to take the next step and connect to it programmatically.

When I ssh into the EC2 MongoDB instance, I need to provide a .pem key file, do I need to do something similar when I connect programmatically?

Upvotes: 4

Views: 2247

Answers (2)

Bijendra
Bijendra

Reputation: 10025

No, you don't need a .pem key for connecting to MongoDB instance.

  • Make sure your Ec2 instance has a public domain or IP. This IP can be used in place of localhost in your node DB configuration.

  • The mongo server should be running on the instance. Check mongo shell to confirm.

  • Create a VPC for better management of instance and define security group with required ports.
  • Use security credentials in your database configuration file.

I would suggest to always have a private IP for database instances and the instance on which your HTTP server is running should have public IP which is mapped with DNS provider. Open minimum ports on DB server mainly :27017 which makes it secure. Both the instances should be inside once VPC since private IP's are only accessible here.

Upvotes: 0

Piyush Patil
Piyush Patil

Reputation: 14533

As per your use case your Mongodb is local on a EC2 instance. So when you connect to Mongodb you will have to SSH using a pem key to EC2 instance in order to connect to the Mongodb. If you want to avoid using pem key each time, you can create a SSH user which can SSH to instance using UN and password.

This is helpful guide to achieve it:

https://coderwall.com/p/j5nk9w/access-ec2-linux-box-over-ssh-without-pem-file

Or another way is connecting using the SSH key.

Upvotes: 1

Related Questions