Omonbude Emmanuel
Software Engineer
HTML/CSS/JAVASCRIPT
PYTHON
DJANGO/DJANGO REST FRAMEWORK
NODE JS
DOCKER, AWS, KUBERNATES
FIREBASE, PostgreSQL, MySQL,Mongo DB
FLUTTER
DART
ANGULAR
TYPESCRIPT

Opening Mongo DB Port for remote connections

Omonbude Emmanuel | April 11, 2024, 9:33 a.m.

63

Introduction

By default, MongoDB only allows local connections for security reasons. However, sometimes you need to access your MongoDB database from a remote location. In this post, we will guide you through the process of opening the MongoDB port for remote connections.

Prerequisites

1. MongoDB installed and running: MongoDB must be installed and running on the server or computer you want to access remotely.
2. Root or administrative privileges: You need root or administrative privileges to edit the MongoDB configuration file and configure the firewall.
3. Access to the MongoDB configuration file: You need access to the MongoDB configuration file (mongod.conf) to make changes.
4. Firewall enabled: The firewall must be enabled on the server or computer to restrict incoming connections.
5. Network connectivity: The server or computer must be connected to the network and have a static IP address or a dynamic IP address that can be accessed remotely.
 

LET'S BEGIN!!


Step 1: Edit the MongoDB Configuration File

The first step is to edit the MongoDB configuration file (mongod.conf) to allow remote connections. You can do this by running the following command:

sudo nano /etc/mongod.conf

Add the following lines to the file:
scroll down to where you have # network interfaces  and replace 127.0.0.1 with 0.0.0.0

net:
    port: 27017
    bindIp: 0.0.0.0

The the first line specifies the port number to use (in this case, the default port 27017) and the  second line allows MongoDB to listen on all available network interfaces.

Step 2: Restart the MongoDB Service

After editing the configuration file, restart the MongoDB service to apply the changes:

sudo systemctl restart mongod

Step 3: Configure the Firewall

Next, you need to configure the firewall to allow incoming connections on the MongoDB port. You can do this by running the following command:

First enable your firewall

sudo ufw enable

 

Then allow the port

sudo ufw allow 27017

This will allow all incoming connections on port 27017.

If you want to allow only a specific ip address, you can  use the command below

sudo ufw allow from ipaddress to any port 27017

Replace with the ip address, this will allow connections to only the ipaddress given

 

Step 4: Test the Remote Connection

Finally, test the remote connection by connecting to your MongoDB database from a remote location using the MongoDB client or any other tool.

Conclusion
 

In this post, we have shown you how to open the MongoDB port for remote connections. Remember to always follow security best practices when allowing remote connections to your database.

© 2024 Omonbude Emmanuel

Omonbude Emmanuel