This guide walks you through connecting a Node.js application to a MongoDB database running on a virtual private server (VPS). You’ll learn how to install MongoDB, start the service, create a database user, and connect from your Node.js code using the official driver. By the end, you’ll have a working connection string and a test script that verifies the connection.
What You’ll Need
- A VPS with Ubuntu 20.04 or 22.04 (or similar Linux distribution) and root or sudo access.
- Node.js and npm installed on your local machine (or on the VPS if you’re developing there).
- Basic familiarity with the command line and SSH.
Step-by-Step
- SSH into your VPS
Open a terminal and run:ssh user@your_server_ip. Replaceuserwith your username andyour_server_ipwith your VPS’s IP address. - Update the system packages
Runsudo apt updateand thensudo apt upgrade -yto ensure all existing packages are up to date. - Install MongoDB
MongoDB is not in the default Ubuntu repositories. Add the official MongoDB repository:curl -fsSL https://www.mongodb.org/static/pgp/server-6.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-6.0.gpg echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-6.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list sudo apt update sudo apt install -y mongodb-org
Note: The repository URL depends on your Ubuntu version. For 20.04 (focal), replace
jammywithfocal. For other versions, check the MongoDB docs. - Start MongoDB and enable it on boot
Runsudo systemctl start mongodto start the service, thensudo systemctl enable mongodto make it start automatically on reboot. Verify withsudo systemctl status mongod– you should seeactive (running). - Create an admin user for MongoDB
Open the MongoDB shell:mongosh. Then switch to the admin database and create a user:use admin db.createUser({ user: "admin", pwd: "your_strong_password", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })Exit the shell with
exit. - Enable authentication
Edit the MongoDB config file:sudo nano /etc/mongod.conf. Find thesecuritysection (or add it) and add:security: authorization: enabled
Save and exit, then restart MongoDB:
sudo systemctl restart mongod. - Create a database and user for your app
Log back into mongosh with the admin user:mongosh -u admin -p your_strong_password --authenticationDatabase admin. Then create a dedicated database and user:use myappdb db.createUser({ user: "appuser", pwd: "app_password", roles: [{ role: "readWrite", db: "myappdb" }] })Exit.
- Open MongoDB port (optional but recommended for remote connections)
By default MongoDB listens on port 27017 on localhost. If you want to connect from your local machine, you need to bind to your VPS’s public IP and open the port in the firewall. Edit/etc/mongod.confand changebindIp: 127.0.0.1tobindIp: 0.0.0.0(or your specific IP). Then restart MongoDB. Usesudo ufw allow 27017if you use UFW. Important: Only do this if you understand the security risks – it exposes your database to the internet. A safer alternative is to use an SSH tunnel. - Install the MongoDB Node.js driver
On your local machine (or where your Node.js app is), create a new project folder and run:npm init -y npm install mongodb
- Write a test connection script
Create a file namedtest.jswith the following content:const { MongoClient } = require('mongodb'); const uri = "mongodb://appuser:app_password@your_server_ip:27017/myappdb?authSource=myappdb"; const client = new MongoClient(uri); async function run() { try { await client.connect(); const db = client.db("myappdb"); const collection = db.collection("test"); await collection.insertOne({ message: "Hello from Node.js" }); const doc = await collection.findOne({ message: "Hello from Node.js" }); console.log("Connection successful. Found:", doc); } finally { await client.close(); } } run().catch(console.dir);Replace
app_passwordandyour_server_ipwith your actual values. - Run the test
Executenode test.js. If everything is set up correctly, you’ll see the inserted document printed. If not, proceed to the Troubleshooting section.
Common Mistakes
- Using the wrong MongoDB version repository – The repository URL must match your Ubuntu version. Using the wrong one will cause installation errors.
- Forgetting to enable authentication – If you skip step 6, MongoDB will accept connections without a password, which is a security risk.
- Binding to 0.0.0.0 without a firewall – This exposes your database to the entire internet. Always configure UFW or a cloud security group to restrict access.
- Incorrect connection string – The
authSourceparameter must match the database where the user was created (oftenadminor the app database). If you created the user inadmin, useauthSource=admin. - Using
localhostin the connection string when connecting remotely – If your Node.js app is on a different machine, you must use the VPS’s public IP or hostname.
Tips
- Use environment variables to store your connection string and password. Never hardcode credentials in your source code.
- For production, consider using MongoDB Atlas (cloud-hosted) instead of self-managing on a VPS – it handles backups, monitoring, and scaling.
- Regularly back up your MongoDB data using
mongodumpor a scheduled cron job. - Use a firewall that only allows connections from your app server’s IP, not from anywhere.
- If you’re connecting from a local development machine, an SSH tunnel is a secure and simple alternative to opening the port.
Troubleshooting
- Connection refused – Check that MongoDB is running (
sudo systemctl status mongod). Also verify that the port is open:sudo netstat -tulpn | grep 27017. If it’s listening only on 127.0.0.1, you haven’t changed the bindIp correctly. - Authentication failed – Double-check the username, password, and
authSource. If you created the user inadmin, useauthSource=adminin the URI. Also ensure you enabled authorization in the config file. - Timeout when connecting – This usually indicates a firewall blocking the port. Check UFW rules (
sudo ufw status) and cloud provider security groups. Also confirm the VPS’s public IP is correct and that the server is reachable (tryping). - Error:
Cannot connect to MongoDBafter restart – Check the MongoDB logs:sudo journalctl -u mongod -n 50. Look for errors about config file syntax or permission issues. - MongoDB won’t start – Run
sudo systemctl status mongodto see the error. Common causes: missing/var/lib/mongodbdirectory, permission issues, or a malformed config file. Trysudo mongod --config /etc/mongod.confto see the error directly.
Frequently Asked Questions
Can I connect to MongoDB from a different machine than the VPS?
Yes, but you need to bind MongoDB to a non-localhost IP and open the port in the firewall. Always restrict access to your app server’s IP for security.
What is the difference between mongodb and mongosh?
mongodb is the daemon (server), while mongosh is the interactive shell. You use mongosh to run commands like creating users.
Do I need to install MongoDB on the same VPS as Node.js?
No, you can install them on separate servers. Just make sure the connection string points to the correct IP and port.
How do I secure my MongoDB connection?
Enable authentication, use a strong password, bind to a specific IP, and use a firewall. For extra security, use TLS/SSL or an SSH tunnel.
What is the default port for MongoDB?
27017. You can change it in the config file, but then you must update your connection string accordingly.
Can I use Mongoose instead of the native driver?
Yes, Mongoose is a popular ODM that wraps the native driver. The connection string is the same; you just use mongoose.connect(uri) instead.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Google Assistant IFTTT Recipes: 7 Useful Automations
- OLED TVs in Dark Rooms: Why They Look Better and When They Don’t
- Philips DST7060/20 7000 Series Iron: Specs & Fit
- Coal Fueled Jet Aircraft: Could It Work?675 L
- Remote Desktop on Raspberry Pi: How to Enable It
- Word Select Last Line in Paragraph?