Here is how to enable remote access to MongoDB in cPanel:
- Open port on the firewall
- Enable remote access in mongodb.conf
- 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
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
mongodb.conf to enable remote access
Create Admin User for MongoDB
- 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: