Hi everyone! Even though my databases have always been secured with a complex password and access control, I kept seeing failing connections from various shady servers on the Internet. Today I decided to put an end to these filthy and unsuccessful attempts to access my MongoDB instances once and for all. And I'll show you how I've done it.
I'm going to assume that you run a Debian-based server (e.g. Ubuntu). This tutorial will work best for this typical configuration. Also, I won't go over how you can install MongoDB, for that check out the "Setting up MongoDB" section of another tutorial of mine. Also, if you remove the MongoDB parts of this tutorial, you can get a pretty well-secured general purpose server!
- Make sure to add password-protected users to the MongoDB with the correct permissions that your services will use to access the databases. E.g. if you have a statistics server that just reads the DB from time to time, don't give it
- Make sure that you have
enabled. Here are the docs.
- Your services will probably require access to the database over the Internet, so feel free to set
net.bindIpto the correct IP addresses, including
127.0.0.1. Here are the docs. We will restrict the IP addresses that can access the database a bit later.
fail2ban. You can also configure it, but even the default configuration is most likely sufficient.
- From now on, only connect to the database for the debug purposes from your local machine through an SSH tunnel. No more unrestricted dynamic IP addresses that can access the database.
- Make sure you have password SSH authentication off and you're connecting to the VPS as a well-restricted user, almost never as
root! Find the instructions on how to set it up in the "Setting up the VPS" section of my other tutorial.
- Configure and enable
ufw. You would want to restrict all incoming traffic, allow SSH port incoming traffic (the default port is
22), allow MongoDB connection port incoming traffic (the default port is
27017) from specific IP's that will need access (e.g. the statistics server and your backend). See the command below to do so. Then just restart the
ufw. If you're running other things that should be accessible from the Internet, adjust
sudo ufw allow from trusted_server_ip to any port 27017
That's it! Your MongoDB is as secure as you'd want it to be. What to read next? I'd suggest checking out this great tutorial on the same topic in case I missed anything. Cheers!
Subscribe to Golden Borodutch
Get the latest posts delivered right to your inbox
And try out Todorant. It's my main project — a smart todo list that tricks the primitive part of the brain to get things done. It is the only thing that helped me to become as productive as I am right now.