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!

  1. 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 write rights.
  2. Make sure that you have security.authorization in the /etc/mongod.conf set to enabled. Here are the docs.
  3. Your services will probably require access to the database over the Internet, so feel free to set net.bindIp to the correct IP addresses, including Here are the docs. We will restrict the IP addresses that can access the database a bit later.
  4. Install fail2ban. You can also configure it, but even the default configuration is most likely sufficient.
  5. 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.
  6. 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.
  7. 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 ufw accordingly.
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!