Remote Access and DB Authentication

It is better to enable authentication on MongoDB to make it more secure, and also to allow remote access.

On your server open the file: /etc/mongod.conf

Change the Binding IP to

bindIp: 127.0.0.1,10.11.12.13

With the second IP after the coma being the IP of your server where the API and mongo are installed. This will allow remote access to your MongoDB.

Add these lines in the conf file

security:
  authorization: "enabled"

This will prevent connecting without a username/password. You will instead need to use one of the users you created during Mongo Installation.

Restart mongo to enable your conf changes

systemctl restart mongod

Make sure you didn't break anything by changing the config

systemctl status mongod

Now you can connect to your database from your PC, in Mongo Compass, using a string similar to this one

mongodb://[user]:[password]@[hosturl]:27017/[database]?authSource=admin

For Example

mongodb://root:123456789@survival-engine.com:27017/userdb?authSource=admin

The host URL can either be a domain or IP address.

Now also restart your NodeJS app to make sure it can still connect to Mongo. When testing something you can start the app normally with node server.js to see the errors in console instead of using forever.

Firewall setup

It’s good to block the port you don’t use on your server, from the command line, you can run

ufw allow ssh
ufw allow http
ufw allow https
ufw enable

http will open port 80, and https will open port 443

And to check the status of your firewall:

ufw status

Be sure to always run allow ssh before enabling the firewall, otherwise you will lose your putty connection and won’t be able to connect anymore.

If you also want to open a direct access to MongoDB (to use in Mongo Compass), you can enable port 27017 but only for your IP address.

ufw allow from 1.2.3.4 to any port 27017

Important to replace 1.2.3.4 by your own external IP address.

27017 is the default port for Mongo so no need to change it.

It will open port 27017 but only for requests coming from your IP address. This can be really useful to read the Database on your PC for development, you can turn off the access when going live.

Last updated