
How to Deploy MongoDB on VPS?
MongoDB is one of the most popular NoSQL databases used in modern web applications. If you're a beginner working on a full stack app and ready to deploy your backend to a VPS (like DigitalOcean, Linode, or Hetzner), you'll likely need to host MongoDB on your server too.
In this guide, you’ll learn step-by-step how to deploy MongoDB on a Linux-based VPS — securely and efficiently.
🛠️ What You'll Need
- A VPS running Ubuntu 20.04 or later
- Root (or sudo) access
- Basic terminal/SSH knowledge
🧱 Step 1: Connect to Your VPS via SSH
ssh root@your-vps-ip
📥 Step 2: Install MongoDB
🔄 Update Packages
sudo apt update && sudo apt upgrade -y
🔧 Add MongoDB Official Repository
curl -fsSL https://pgp.mongodb.com/server-6.0.asc | \\
sudo gpg -o /usr/share/keyrings/mongodb-server-6.0.gpg \\
--dearmor
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-6.0.gpg ] \\
https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | \\
sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
📦 Install MongoDB
sudo apt update
sudo apt install -y mongodb-org
🚀 Step 3: Start and Enable MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod
🔐 Step 4: Secure Your MongoDB
sudo nano /etc/mongod.conf
👤 Step 5: Create MongoDB Admin User
mongosh
use admin
db.createUser({
user: "admin",
pwd: "strongpassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
✅ Step 6: Enable Authentication
sudo nano /etc/mongod.conf
🌐 Step 7: Allow Firewall Access (Optional)
sudo ufw allow from <your-ip> to any port 27017
sudo ufw enable
🌍 Step 8: Connect Remotely (From Your App)
MONGO_URI=mongodb://admin:strongpassword@your-vps-ip:27017/admin
🧪 Step 9: Test the Connection
npm run dev
🎯 Conclusion
Congrats! You've now deployed and secured MongoDB on your own VPS. This is a big step toward becoming a full stack developer with production-ready skills.
💬 What’s Next?
- 👉 Comment below with your questions or tips
- 🔗 Share with fellow developers
- 📬 Subscribe to CodeJourneyWithAamir for more full stack tutorials!
Hi Everyone, please do not spam in comments.