Software DevelopmentHow To Configure Remote Access for MongoDB on Ubuntu

How To Configure Remote Access for MongoDB on Ubuntu

MongoDB is a free, open-source and document oriented dtabase commonly used in modern web applications. By default, MongoDB listens on localhost and is configured to allow connection only from localhost. If your database and application are hosted on diferrent servers then you may need to configure remote access for MongoDB.

In this post, we will show you how to configure MongoDB for remote connection and allow only trusted IPs to connect to MongoDB.

Prerequisites

  • A server running Ubuntu 20.04
  • A root password is configured on the server.

Getting Started

Before starting, it is recommended to update your system package chache with the latest version. You can update them with the following command:

apt-get update -y

Once your server is updated, install other required packages with the following command:

apt-get install curl gnupg2 nano -y

Once all the required packages are installed, you can proceed to install MongoDB server.

Install MongoDB

By default, the latest version of MongoDB is not included in the Ubuntu default repository. So you will need to add the MongoDB official repository to your system.

First, download and add the GPG key with the following command:

curl -fsSL https://www.mongodb.org/static/pgp/server-4.4.asc | apt-key add -

Once the key is added, you can check it with the following command:

apt-key list

You should get the following output:

/etc/apt/trusted.gpg

--------------------

pub   rsa4096 2019-05-28 [SC] [expires: 2024-05-26]

      2069 1EEC 3521 6C63 CAF6  6CE1 6564 08E3 90CF B1F5

uid           [ unknown] MongoDB 4.4 Release Signing Key <[email protected]>




/etc/apt/trusted.gpg.d/ubuntu-keyring-2012-archive.gpg

------------------------------------------------------

Next, add the MongoDB repository to the APT with the following command:

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list

Next, update the APT cache and install the MongoDB using the following command:

apt-get update -y

apt-get install mongodb-org -y

Once the MongoDB is installed, start the MongoDB service and enable it to start at system reboot with the following command:

systemctl start mongod
systemctl enable mongod

You can also check the MongoDB database using the following command:

mongo --eval 'db.runCommand({ connectionStatus: 1 })'

You should get the following output:

MongoDB shell version v4.4.4

connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

Implicit session: session { "id" : UUID("920f47e2-1c3e-45a9-9909-278176eea99c") }

MongoDB server version: 4.4.4

{

"authInfo" : {

"authenticatedUsers" : [ ],

"authenticatedUserRoles" : [ ]

},

"ok" : 1

}

At this point, MongoDB is installed and running.

Allow MongoDB Remote Connection

By default, MongoDB is configured to listen on localhost on port 27017. You can verify it with the following command:

ss -antpl | grep 27017

You should get the following output:

LISTEN    0         4096             127.0.0.1:27017            0.0.0.0:*        users:(("mongod",pid=44648,fd=10))                                   

Next, edit the MongoDB main configuration file and change the bindIp:

nano /etc/mongod.conf

Change the following lines:

net:

  port: 27017

  bindIp: 127.0.0.1,mongodb-server-ip

Save and close the file then restart the MongoDB service to apply the changes:

systemctl restart mongod

You can also verify the status of MongoDB service using the following command:

systemctl status mongod

You should see the following output:

mongod.service - MongoDB Database Server

     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)

     Active: active (running) since Sat 2021-02-27 13:10:08 UTC; 12min ago

       Docs: https://docs.mongodb.org/manual

   Main PID: 44762 (mongod)

     Memory: 163.3M

     CGroup: /system.slice/mongod.service

             └─44762 /usr/bin/mongod --config /etc/mongod.conf




Feb 27 13:10:08 email.linuxbuz.com systemd[1]: Started MongoDB Database Server.

Feb 27 13:10:38 email.linuxbuz.com systemd[1]: /lib/systemd/system/mongod.service:12: PIDFile= references a path below legacy directory /var/r>

Feb 27 13:10:38 email.linuxbuz.com systemd[1]: /lib/systemd/system/mongod.service:12: PIDFile= references a path below legacy directory /var/r>

Feb 27 13:10:42 email.linuxbuz.com systemd[1]: /lib/systemd/system/mongod.service:12: PIDFile= references a path below legacy directory /var/r>

Feb 27 13:10:42 email.linuxbuz.com systemd[1]: /lib/systemd/system/mongod.service:12: PIDFile= references a path below legacy directory /var/r>

lines 1-14/14 (END)

Now, verify the MongoDB listening IP with the following command:

ss -antpl | grep 27017

You should get the following output:

LISTEN    0         4096             127.0.0.1:27017            0.0.0.0:*        users:(("mongod",pid=44762,fd=11))                                             

LISTEN    0         4096         mongodb-server-ip:27017            0.0.0.0:*        users:(("mongod",pid=44762,fd=10))

 

Configure Firewall

MongoDB listens on port 27017. So you will need to allow this port to your trusted client IP through the firewall.

You can allow it with the following command:

ufw allow from trusted-client-ip to any port 27017

ufw allow from mongodb-server-ip to any port 27017

Next, reload the UFW firewall to apply the changes:

ufw reload

You can also check the status of the UFW firewall with the following command:

ufw status

You should get the following output:

Status: active

To                         Action      From

--                         ------      ----

22/tcp                     ALLOW       Anywhere                  

27017                      ALLOW       mongodb-server-ip             

22/tcp (v6)                ALLOW       Anywhere (v6)

Verify MongoDB Remote Connectivity

Now, log in to the remote system, and test the MongoDB connectivity using the following command:

nc -zv mongodb-server-ip 27017

If everything is fine, you should get the following output:

Connection to mongodb-server-ip 27017 port [tcp/*] succeeded!

You can also connect the MongoDB server directly using the following command:

mongo "mongodb://mongodb-server-ip:27017"

You should get the following output:

MongoDB shell version v4.4.4

connecting to: mongodb://mongodb-server-ip:27017/?compressors=disabled&gssapiServiceName=mongodb

Implicit session: session { "id" : UUID("a73443f2-25ae-41e3-ad2c-f01e94b36f29") }

MongoDB server version: 4.4.4

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

https://docs.mongodb.com/

Questions? Try the MongoDB Developer Community Forums

https://community.mongodb.com

---

The server generated these startup warnings when booting: 

        2021-02-27T13:10:08.589+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem

        2021-02-27T13:10:09.759+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted

---

---

        Enable MongoDB's free cloud-based monitoring service, which will then receive and display

        metrics about your deployment (disk utilization, CPU, operation statistics, etc).




        The monitoring data will be available on a MongoDB website with a unique URL accessible to you

        and anyone you share the URL with. MongoDB may use this information to make product

        improvements and to suggest MongoDB products and deployment options to you.




        To enable free monitoring, run the following command: db.enableFreeMonitoring()

        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()

---

>

 

Conclusion

In the above guide, you learned how to configured MongoDB to allow remote connection from the trusted IP. You can now connect and manage the MongoDB server remotely from the trusted IP. I hope this guide will help you in the production environment.

Also Read: How to Deploy A Go Application With Docker On Ubuntu

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -