How to enable remote access to MongoDB 🍃 in cPanel

How to enable remote access to MongoDB 🍃 in cPanel

Here is how to enable remote access to MongoDB in cPanel:

  1. Open port on the firewall
  2. Enable remote access in mongodb.conf
  3. Create a new admin user for mongodb

Open default MongoDB port 27017 on firewall

Default port for mongodb is 27017 so we need to allow incoming and outgoing connections to this port:

Under ConfigServer Firewall (CSF) go to Firewall Configuration and add port number 27017 in both TCP_IN and TCP_OUT

firewall configuration csf
open port on firewall

Save the changes and restart both lfd and csf services.


Enable remote connection to MongoDB

By default mongodb has remote access disabled and is configured to accept connections on localhost only.

nano /etc/mongod.conf

and under network interfaces put bindIp: 0.0.0.0 to accept connections on both hostname and the IP

Default mongod.conf

127.0.0.1

mongodb.conf to enable remote access

0.0.0.0

Create Admin User for MongoDB

  1. start mongod without access control
mongod --port 27017 --dbpath /data/db1

TIP: db_path can be found in the conf file: grep dbPath /etc/mongod.conf

2. connect to mongodb

mongo --port 27017

3. create new admin user for mongodb

use admin
db.createUser(

  {

    user: "USERNAME-HERE",

    pwd: "SOME-STRONG-PASSWORD-HERE",

    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]

  }

)

4. restart mongodb with access control

mongod --auth --port 27017 --dbpath /data/db1

5. now test the connection

mongo --port 27017 -u "USERNAME-HERE" -p "SOME-STRONG-PASSWORD-HERE" \
  --authenticationDatabase "admin"

To test the remote connection you can use a tool such as MongoDB Compass:

Written by
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.