Connecting to MongoDB on an EC2 instance

In the age of cloud computing, hosting databases on platforms like AWS has become commonplace. Amazon EC2 provides a flexible environment for running databases like MongoDB. However, accessing these databases remotely requires a mix of configuration and, importantly, security measures to ensure that your data remains protected. In this post, we’ll guide you through the steps to connect to your MongoDB hosted on an EC2 instance from your local machine, while also emphasizing secure practices.


Before we dive into the connection process, let’s ensure you have everything in place to follow along:

AWS Account and EC2 Knowledge: You should have an active AWS account and a basic understanding of EC2. This involves knowing how to launch instances, navigate the EC2 dashboard, and access instances using SSH.

MongoDB on EC2: A running EC2 instance with MongoDB installed. If you haven’t installed MongoDB yet, here’s a guide from the official MongoDB documentation.

Local MongoDB Client: On your local machine, you’ll need a MongoDB client to connect to the remote database. You can either use the official MongoDB client or GUI tools like Robo 3T.

SSH Access: Ensure you have SSH access to your EC2 instance. Typically, this means you have the private .pem key file provided when you created your EC2 instance.

Setting up Security Group for MongoDB on EC2:
Security Groups in AWS function as a virtual firewall to control inbound and outbound traffic to resources, such as EC2 instances. To enable connectivity to MongoDB on your EC2 instance, you’ll need to adjust the associated Security Group.

Navigate to AWS Management Console: Log in to your AWS account and head over to the EC2 Dashboard.

Locate the Security Group: On the left-hand menu, find and click on ‘Security Groups’. Identify the security group associated with your MongoDB EC2 instance.

Modify Inbound Rules:

Select the security group by clicking the checkbox next to it.

In the bottom pane, switch to the ‘Inbound rules’ tab.

Click on ‘Edit inbound rules’.

Click ‘Add Rule’ and set the following:

Type: Custom TCP
Port Range: 27017 (MongoDB’s default port)
Source: Custom, and enter your local machine’s IP. You can use “What’s my IP” on Google to determine your public IP. Note: Restricting this to your IP is more secure than allowing all (
Click ‘Save rules’.

The Security Group is now configured to allow connections to MongoDB from your local machine. Remember, this is just one part of the equation; ensuring MongoDB itself is correctly configured for remote connections is equally critical, which we’ll address in the following sections.

Configuring MongoDB for External Access

Merely adjusting the AWS Security Group isn’t sufficient. MongoDB’s default configuration binds it to, which means it only listens for connections from the local machine. We’ll need to modify this to allow remote connections:

Access MongoDB Configuration: SSH into your EC2 instance:

ssh -i /path/to/your/private-key.pem ec2-user@your-ec2-ip

Edit the Configuration File: Use a text editor (like Nano or Vim) to modify the mongod.conf file, typically found at /etc/mongod.conf:

sudo nano /etc/mongod.conf

Modify bindIp:
Locate the net section. Change or add the bindIp option to Note that while this allows connections from any IP, it’s just a starting point – you’d ideally list only the IPs you want to allow:

  port: 27017

Restart MongoDB: Save your changes and restart the MongoDB service to apply them:

sudo systemctl restart mongod

Connecting to MongoDB from Your Local Machine

Now that everything’s set up on the server side, let’s get connected from your local computer:

Using the Mongo Client: Run the following command, replacing your-ec2-ip with the public IP of your EC2 instance:

mongo --host your-ec2-ip --port 27017

Test the Connection: Once connected, run a simple command to list the databases:

show dbs

Optional GUI Tools: If you prefer a graphical interface, tools like Robo 3T or MongoDB Compass can be used. Simply set up a new connection in the tool of your choice, pointing it to your-ec2-ip and port 27017.

Security Considerations:

While the steps above get you connected, security should always be at the forefront:

  1. Never Expose MongoDB Openly: Limiting exposure by binding only to necessary IP addresses or using a VPN/VPC peering ensures that your database isn’t an open target.
  2. Set Up Authentication: A MongoDB instance without authentication is a vulnerable one. Ensure you create administrative and user accounts:
    • Start MongoDB with authentication enabled by adding the --auth flag or update the configuration file.
    • Create users with specific roles and permissions. For instance, an administrative user and a separate user for application access.
  3. Data Encryption: Consider enabling:
    • In-transit encryption by using TLS/SSL for client-server connections.
    • At-rest encryption to secure data stored on disk.
  4. Backup Regularly: Regular backups ensure data integrity and availability. Tools like mongodump can be automated to take periodic backups.

Using an SSH Tunnel for Secure Connection (Alternative Method):

Directly connecting to MongoDB, even with the precautions listed, can sometimes feel exposed. An SSH tunnel can add an additional layer of security by funneling the database connection through a secure shell (SSH) connection.

  1. What is an SSH Tunnel?: An SSH tunnel works like a secured pipe between your local machine and the remote server. It forwards local ports to ports on your server, effectively wrapping the traffic in an encrypted SSH layer.
  2. Setting Up the Tunnel: Use this command on your local machine:
ssh -L 27017:localhost:27017 -i /path/to/your/private-key.pem ec2-user@your-ec2-ip

This forwards your local port 27017 to the EC2’s port 27017 through SSH.

Connecting to MongoDB: With the tunnel in place, connect as if MongoDB was running on your local machine:

mongo --host localhost --port 27017

Common Troubleshooting Tips:

Even with the best instructions, things don’t always go as planned. Here are some common issues and how to address them:

  1. Connection Timeouts or Refusals:
    • Firewall Issues: Ensure your EC2’s security group permits traffic on port 27017.
    • MongoDB Configuration: Ensure mongod.conf is correctly set to allow connections from your IP.
  2. Authentication Failures:
    • Ensure you’re using the correct username and password.
    • If MongoDB is set up with --auth, ensure you have the necessary roles and permissions.
  3. Logs are Your Friend: Most issues with MongoDB can be diagnosed by examining the logs. Check the logs using:
sudo cat /var/log/mongodb/mongod.log


Connecting to a MongoDB instance on EC2 from a local machine offers flexibility and efficiency for various tasks, from development to data analysis. While the process can be straightforward, security must never be an afterthought. Whether it’s the use of SSH tunnels, enabling authentication, or regularly backing up data, taking those extra steps to secure your database can save a lot of headaches in the future.

We hope this guide has provided you with a clear path to connect securely to your MongoDB instance on EC2. If you have further questions or experiences to share, do engage in the comments section below!

Frequently Asked Questions (FAQ):

  1. Why can’t I connect to MongoDB even after configuring everything correctly? Answer: Multiple factors might prevent a successful connection: firewall rules, incorrect bind IP in MongoDB configuration, or AWS security group settings. Always check logs and ensure that both AWS and MongoDB configurations permit the connection from your IP.
  2. Is it safe to bind MongoDB to Binding allows connections from any IP, which can be risky. It’s recommended to bind only to specific, known IPs or use VPNs or SSH tunnels to secure the connection.
  3. Why use an SSH tunnel when AWS security groups already restrict IP access? Answer: While AWS security groups do restrict access, SSH tunnels add an additional layer of encryption and protection. It’s an added safeguard, especially when dealing with sensitive data.
  4. How often should I back up my MongoDB data? Answer: The frequency of backups depends on the criticality of your data and how often it changes. For highly dynamic databases, daily backups or even more frequent snapshots might be suitable. Always ensure you test backups to confirm data integrity.
  5. I’ve heard MongoDB has been a target for ransomware attacks. How can I protect my data? Answer: Secure your MongoDB instance by enabling authentication, regularly updating to the latest version, restricting IP access, using encryption, and taking regular backups. These measures significantly reduce the risk of unauthorized access and data loss.
  6. Can I connect to MongoDB on EC2 using a GUI tool? Answer: Absolutely! Tools like Robo 3T, MongoDB Compass, and others allow you to connect to remote MongoDB instances. Just ensure the tool supports connecting through your chosen security measures (like SSH tunnels if you’re using them).
  7. Does MongoDB support encryption for data in transit and at rest? Answer: Yes, MongoDB offers support for both in-transit and at-rest encryption. For in-transit, you can use TLS/SSL. For at-rest encryption, the WiredTiger storage engine’s native encryption can be utilized.
  8. Are there costs associated with data transfer when connecting to MongoDB on EC2?Answer: AWS generally charges for data transfer out of their services to the internet or to other regions. Always consult the AWS pricing documentation for the latest details.

Atiqur Rahman

I am MD. Atiqur Rahman graduated from BUET and is an AWS-certified solutions architect. I have successfully achieved 6 certifications from AWS including Cloud Practitioner, Solutions Architect, SysOps Administrator, and Developer Associate. I have more than 8 years of working experience as a DevOps engineer designing complex SAAS applications.

Leave a Reply