If you have MongoDB running on your Linux Server in Amazon EC2, Amazon Lightsail, Vultr or any server, you will see there is no simple tutorial out there explaining how to setup user authentication for Mongo so that you can read and write to your MongoDB server from your Laptop or from other Backend Server. If so we will show you a way to do that.
If you have not installed mongoDB yet, go to this link
1. Setup your user for your DB
First ssh
into your server and enter the mongo shell by typing mongo
. For this example, I will set up a user named feedtekuser and give that user read & write access to the yourdb
database.
use yourdb
db.createUser({
user: 'feedtekuser',
pwd: 'secretPassword',
roles: [{ role: 'readWrite', db:'yourdb'}]
})
2. Enable auth and open MongoDB access up to all IPs
Edit your MongoDB config file. On Ubuntu:
sudo vim /etc/mongod.conf
- Look for the
bindIp
, which is currently limiting MongoDB connections to localhost: - Change it to
bindIp: 0.0.0.0
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0 <- change it to 0.0.0.0
- Scroll down to the
#security:
section and add the following line. Make sure to un-comment thesecurity:
line.
security:
authorization: 'enabled'
3. Open port 27017 on your EC2 instance
- Go to your EC2 dashboard: https://console.aws.amazon.com/ec2/
- Go to
Instances
and scroll down to see your instance’s Security Groups. Eg, it will be something likelaunch-wizard-4
- Go to
Netword & Security
->Security Groups
->Inbound
tab ->Edit
button. - Make a new Custom TCP on port 27017, Source: Anywhere, 0.0.0.0/0
4. Last step: restart mongo daemon (mongod)
sudo service mongod restart
Make sure you can still log in with mongo
while ssh’d into the box.
If anything goes wrong, look at the log: tail -f /var/log/mongodb/mongod.log
(note: non-Ubuntu machines will keep the log in another directory…)
Logging in using the mongo
shell on your laptop
You can close out of ssh and go back to your local console. To enter the remote Mongo database we just set up, you can use the mongo shell:
mongo -u feedtekuser-p secretPassword 123.45.67.89/yourdb
Where 123.45.67.89
is your server’s public IP address.
Now you can read and write within the yourdb
database from your nodejs projects by using this string connection:
"mongodb://feedtekuser:[email protected]/yourdb"