Around New Heights School, Dawhenya, Greater Accra, Ghana

Connecting remotely to a Mongo Database on a VPS

Hello guys! I hope you are doing great. If you’ve ever had to modify data in your MongoDB database on a VPS during development, you would realize that it can be a pain.  You would have to first SSH into the VPS, login to MongoDB , select a database, and write commands in a very uncomfortable way. After doing this over and over, I got tired and decided to find a way to connect remotely from my local PC. Once you are able to do this, the possibilities are endless! You could connect to a remote database with tools like MongoDB Compass  and Robo 3T which will offer you a graphical interface for working with your database.  If you want be able to do that follow along.

Steps involved

    1. Create a new mongo db user.
    2. Enable authentication in mongodb and make MongoDB accessible to all IPs
    3. Open up MongoDB port in firewall.
    4. Connect to database from local PC.

 

Step 1: Create a new MongoDB user

Open terminal on your local PC and SSH into your linux VPS with your user and server IP like so:  ssh yourusername@yourhostip Once logged in, type mongo  and press enter to access the Mongo shell and type the following to create a user.

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

Exit Mongo shell by typing exit and pressing enter.
exit

Step 2: Enable authentication in mongodb and make MongoDB accessible to all IPs

Open /etc/mongod.conf with nano.

 nano /etc/mongod.conf

Look for a commented line with security and modify it like below

security:
    authorization: enabled

Look for bindIp and change IP to 0.0.0.0 like so.

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

Save and exit with Ctrl+X and hit enter.

Now restart Mongo.
systemctl restart mongod

Step 3: Open up MongoDB port in firewall

Open Mongo db port 27017 in firewall so it can be accessed from a remote IP

firewall-cmd --permanent --zone=public --add-port=27017/tcp

Now Download and install Mongo compass

Step 4: Connect to database from local PC

Connect to the database using a URL like the one in the image. Note that the URL has mongodb username , mongodb password, server Ip and mongodb port

This is the connection string

mongodb://mongoDBusername:mongoDBpassword@serverIP:27017/?authSource=admin&readPreference=primary&appname=MongoDB%20Compass&ssl=false

That’s it Enjoy!!!

Leave a comment