Expose MongoDB publicly, secure it with a password, and connect from MongoDB Compass

Great — you're almost there! Here's how to expose MongoDB publicly, secure it with a password, and connect from MongoDB Compass on your local machine.


⚠️ IMPORTANT WARNING

MongoDB is not safe to expose publicly by default. We’ll enable authentication, bind to 0.0.0.0, and optionally use a firewall to restrict access only to your IP.


✅ Step-by-Step Guide

🔒 1. Enable MongoDB Authentication

Edit the MongoDB config file:

sudo nano /etc/mongod.conf

Find this section and set:

security:
  authorization: enabled

Also, find the net section and change the bind IP:

net:
  port: 27017
  bindIp: 0.0.0.0  # allow external access

Then restart MongoDB:

sudo systemctl restart mongod

👤 2. Create an Admin User

Start a Mongo shell without auth (because auth isn't enforced yet):

mongosh

Then run:

use admin

db.createUser({
  user: "myadmin",
  pwd: "StrongPassword123!",
  roles: [ { role: "root", db: "admin" } ]
})

Exit Mongo shell:

exit

Restart MongoDB one more time to enforce auth:

sudo systemctl restart mongod

🔥 3. [RECOMMENDED] Restrict MongoDB Access to Your IP Only

Allow only your IP (from home/office) to connect via port 27017:

sudo ufw allow from YOUR_IP_ADDRESS to any port 27017

Check your IP at: https://whatismyipaddress.com/

Enable UFW if it’s not already:

sudo ufw enable

🧭 4. Connect from MongoDB Compass (Local Machine)

  1. Open MongoDB Compass

  2. Connection string:

    mongodb://myadmin:StrongPassword123!@YOUR_SERVER_IP:27017/admin
    
  3. Click Connect


✅ Done! Checklist Recap

| Step | Status | | ----------------------------------------------------- | ------ | | Allow remote connections (bindIp 0.0.0.0) | ✅ | | Enable authentication | ✅ | | Create admin user | ✅ | | Restart MongoDB | ✅ | | Open port 27017 with firewall (restricted to your IP) | ✅ | | Test in MongoDB Compass | ✅ |

PARTNER WITH US TO CREATE A COMPELLING NARRATIVE
FOR YOUR BRAND!

Let's bring your ideas to life, start collaborating with our creative agency and turn your vision into reality.