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
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
This will prevent connecting without a username/password. You will instead need to use one of the users you created during Mongo Installation.
Important: Changing the binding IP will allow anyone to try to connect directly to your database from anywhere, as long as they have the password. It can be useful for development if you want to read your database from Mongo Canvas, but it is also an increased security risk. If you allow remote connection you should also setup your server firewall properly so that it blocks requests that don't come from your IP for the MongoDB port. See the Firewall section below.
Restart mongo to enable your conf changes
Make sure you didn't break anything by changing the config
Now you can connect to your database from your PC, in Mongo Compass, using a string similar to this one
For Example
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
http will open port 80, and https will open port 443
And to check the status of your firewall:
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.
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