MongoDB Installation on AWS Ubuntu EC2: Complete Beginner’s Guide

MongoDB is one of the most popular NoSQL databases used for modern, scalable applications. This guide will help you install MongoDB on an AWS Ubuntu EC2 instance using the official MongoDB repository.
1. Update Your Ubuntu Server

SSH into your EC2 instance:

ssh -i your-key.pem ubuntu@your-ec2-public-ip

Update packages:

sudo apt update && sudo apt upgrade -y
2. Import MongoDB Public GPG Key
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
–dearmor
3. Add the MongoDB Repository for Ubuntu
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
Replace jammy with your Ubuntu version if needed:
Ubuntu 22.04 → jammy
Ubuntu 20.04 → focal
4. Install MongoDB
sudo apt update
sudo apt install -y mongodb-org
5. Start & Enable MongoDB Service
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod

If status shows active (running) → MongoDB is installed successfully.

6. Allow MongoDB Port on AWS Security Group

MongoDB default port:

27017

Go to AWS Console → EC2 → Security Groups → Inbound → Add:

Type Protocol Port Source
Custom TCP TCP 27017 Your IP
⚠️ Do NOT open 0.0.0.0/0 for production.
Whitelist specific IPs only.
7. Test MongoDB Shell
mongosh

To show databases:

show dbs
8. Enable Remote Access (Optional)

Edit config file:

sudo nano /etc/mongod.conf

Find:

bindIp: 127.0.0.1

Change to:

bindIp: 0.0.0.0

Restart:

sudo systemctl restart mongod
⚠️ Secure MongoDB with users if enabling remote access.
9. Create Admin User (Highly Recommended)

Inside the Mongo shell:

use admin
db.createUser({
user: “admin”,
pwd: “StrongPassword123”,
roles: [ { role: “root”, db: “admin” } ]
})

Login using:

mongosh -u admin -p StrongPassword123 –authenticationDatabase admin
10. Check MongoDB Logs
sudo tail -f /var/log/mongodb/mongod.log
FAQs

1. Which Ubuntu versions support MongoDB 7.0?

  • Ubuntu 22.04 (Jammy)
  • Ubuntu 20.04 (Focal)

2. Does MongoDB run automatically after a reboot?
Yes, systemctl enable mongod ensures auto-start.

3. What is the default MongoDB port?
27017

4. Why is my remote connection failing?

  • Check:
  • Security Group inbound rules
  • mongod.conf bindIp
  • Service running

Leave a Reply

Your email address will not be published. Required fields are marked *