MongoDB is a powerful NoSQL database widely used for modern web and mobile applications. If youβre running a VPS and want to set up MongoDB for your project, this guide will walk you through the complete process in a simple and practical way.
This tutorial is focused on Ubuntu-based VPS servers (20.04 / 22.04), which are the most commonly used.
β Prerequisites
Before starting, make sure:
- You have a VPS with Ubuntu installed
- You can access it via SSH
- You are logged in as
rootor a sudo user
Connect to your server:
ssh root@your_server_ip
π Step 1: Update Your System
Always start by updating system packages:
sudo apt update && sudo apt upgrade -y
π¦ Step 2: Install Required Packages
MongoDB needs some basic packages to be added first:
sudo apt install -y gnupg curl
π Step 3: Add MongoDB Official GPG Key
Import MongoDBβs public key:
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
π Step 4: Add MongoDB Repository
Now add the official MongoDB repository:
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
Then update again:
sudo apt update
βοΈ Step 5: Install MongoDB
Install MongoDB with:
sudo apt install -y mongodb-org
βΆοΈ Step 6: Start and Enable MongoDB
Start the MongoDB service:
sudo systemctl start mongod
Enable MongoDB to run automatically on boot:
sudo systemctl enable mongod
Check status:
sudo systemctl status mongod
You should see: active (running) β
π§ͺ Step 7: Test MongoDB
Open the Mongo shell:
mongosh
Test command:
show dbs
Exit:
exit
π (Optional but Recommended) Step 8: Secure MongoDB
Edit config:
sudo nano /etc/mongod.conf
Change bind IP (for security):
bindIp: 127.0.0.1
Restart MongoDB:
sudo systemctl restart mongod
To enable authentication later, you can turn on:
security:
authorization: enabled
π (Recommended) Step 9: Create MongoDB User
mongosh
use admin
db.createUser({
user: "admin",
pwd: "STRONG_PASSWORD",
roles: [ { role: "root", db: "admin" } ]
})
Enable auth:
nano /etc/mongod.conf
Add:
security:
authorization: enabled
Restart:
systemctl restart mongod
β Connection string example (Node.js / Laravel)
MONGO_URI=mongodb://admin:password@127.0.0.1:27017/dbname?authSource=admin
π§© Common Issues & Fixes
MongoDB service failed?
Run:
journalctl -xeu mongod
Port issue?
Allow MongoDB in firewall (if needed):
sudo ufw allow 27017
π Conclusion
Your MongoDB server is now successfully installed and running on your VPS. You can connect it with Laravel, Node.js, Python, or any backend service and start building scalable applications.
If you are building APIs, SaaS apps, or real-time platforms, MongoDB on VPS gives you full control, performance, and flexibility.
