To use MongoDB on a Linux server, install the MongoDB package from the official repository, start and enable the mongod service, secure it with authentication and a firewall, then connect using mongosh to create users, databases, and indexes.
This guide covers installation, configuration, security, performance tuning, backups, and troubleshooting for production use.
MongoDB is a high‑performance NoSQL database used for modern web apps, microservices, and analytics. This beginner‑friendly guide explains how to use MongoDB on a Linux server from installation to security hardening, tuning, and backups—so you can run it confidently in production or on a development VPS.

Prerequisites and System Requirements
Before installing, confirm these basics to ensure a smooth setup and optimal performance.
Supported Linux distributions
MongoDB provides official packages for popular distros:
- Ubuntu 22.04/24.04 (Jammy/Noble)
- Debian 12 (Bookworm)
- RHEL 8/9 and compatible (Rocky, AlmaLinux)
Server and network requirements
- 64‑bit CPU, 2+ vCPU, 4–8 GB RAM minimum for small workloads (more for production).
- SSD storage recommended with XFS filesystem.
- Open TCP port 27017 (default) limited to trusted IPs only.
- Sudo/root access, and outbound internet to fetch repos.
Install MongoDB on Linux
The safest way is to use the official MongoDB repository so you receive security updates and the latest stable version.
Ubuntu 22.04/24.04 (APT)
Add the MongoDB repository and install the community edition:
# Import the public key (MongoDB 7.0 example)
wget -qO - https://pgp.mongodb.com/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
# Add the repo (Ubuntu Jammy as example; change jammy to noble for 24.04)
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
sudo apt update
sudo apt install -y mongodb-org
# Start and enable at boot
sudo systemctl enable --now mongod
# Verify
systemctl status mongod --no-pager
mongod --version
Debian 12 (APT)
wget -qO - https://pgp.mongodb.com/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/debian bookworm/mongodb-org/7.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl enable --now mongod
RHEL 8/9, AlmaLinux, Rocky (DNF/YUM)
# Create the repo file
cat | sudo tee /etc/yum.repos.d/mongodb-org-7.0.repo >/dev/null <<'EOF'
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-7.0.asc
EOF
sudo dnf install -y mongodb-org
sudo systemctl enable --now mongod
# On SELinux enforced systems, make sure the port is allowed (default is already labeled)
sudo semanage port -l | grep mongo || true
Tip: If you run into GPG or repo errors, verify distro codename/version matches MongoDB’s supported matrix.
Initial Configuration for Production
Know your directories and config file
- Data: /var/lib/mongo
- Logs: /var/log/mongodb/mongod.log
- Config: /etc/mongod.conf
Any change to /etc/mongod.conf requires a restart: sudo systemctl restart mongod.
Bind to localhost or specific IPs
By default, MongoDB binds to 127.0.0.1 (safe for single‑server development). To allow remote apps, add your server’s private IP and restrict access via firewall.
# /etc/mongod.conf (excerpt)
net:
port: 27017
bindIp: 127.0.0.1,10.0.0.10 # replace with your server's IP
Open the port only to trusted hosts:
# Ubuntu UFW example
sudo ufw allow from 203.0.113.25 to any port 27017 proto tcp
sudo ufw status
# RHEL firewalld example
sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="203.0.113.25" port protocol="tcp" port="27017" accept' --permanent
sudo firewall-cmd --reload
Enable authentication and create the admin user
MongoDB ships with authentication disabled. Turn it on and create a root administrator.
# 1) Create the admin user while auth is OFF (default after install)
mongosh --host 127.0.0.1 --port 27017 admin
db.createUser({
user: "siteAdmin",
pwd: passwordPrompt(),
roles: [ { role: "root", db: "admin" } ]
})
exit
# 2) Enable authorization in mongod.conf
sudo sed -i '/^#*security:/,$!b;/authorization:/c\ authorization: enabled' /etc/mongod.conf || true
# Or edit manually:
# security:
# authorization: enabled
sudo systemctl restart mongod
# 3) Test login
mongosh "mongodb://siteAdmin@127.0.0.1:27017/admin" --password
Basic MongoDB Usage on Linux
Connect with mongosh (local and remote)
# Local
mongosh "mongodb://siteAdmin@127.0.0.1:27017/admin" --password
# Remote from an app server
mongosh "mongodb://appUser@mongo.example.com:27017/appdb?authSource=admin" --password
Create a database, collection, and index
use appdb
db.createUser({ user: "appUser", pwd: passwordPrompt(), roles: [ { role: "readWrite", db: "appdb" } ] })
db.createCollection("orders")
db.orders.insertOne({ orderId: 1001, userId: 42, total: 79.99, createdAt: new Date() })
# Create an index (speeds up queries by userId)
db.orders.createIndex({ userId: 1 })
db.orders.find({ userId: 42 }).explain("executionStats")
Import, export, and backups
# Import JSON/CSV
mongoimport --db appdb --collection users --file users.json --jsonArray
mongoimport --type csv --headerline --db appdb --collection products --file products.csv
# Logical backup and restore (online-friendly)
mongodump --archive=/backups/mdb_$(date +%F).gz --gzip --authenticationDatabase admin -u siteAdmin -p
mongorestore --archive=/backups/mdb_2025-01-01.gz --gzip
Security Best Practices
User and role design
- Use least privilege: app users get readWrite on their database only.
- Separate admin, backup, and monitoring users with distinct roles.
- Rotate passwords and store secrets in a vault.
Enable TLS/SSL for in‑transit encryption
Use certificates to protect credentials and data on the wire. For internal clusters, a private CA is fine; for public endpoints, use a valid CA (e.g., Let’s Encrypt).
# Generate a key and self-signed cert (example)
openssl req -newkey rsa:4096 -nodes -keyout /etc/ssl/private/mongo.key \
-x509 -days 365 -out /etc/ssl/certs/mongo.crt -subj "/CN=mongo.example.com"
cat /etc/ssl/private/mongo.key /etc/ssl/certs/mongo.crt | sudo tee /etc/ssl/mongo.pem >/dev/null
chmod 600 /etc/ssl/mongo.pem
# /etc/mongod.conf (excerpt)
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/mongo.pem
Restart MongoDB and connect with TLS options from clients. For replica sets, also configure a keyFile for internal member authentication.
OS‑level hardening
- Firewall: allow 27017 only from trusted IPs or VPC subnets.
- SELinux/AppArmor: leave enforced; allow only necessary contexts and paths.
- Disable password SSH logins; use key‑based SSH.
- Enable automatic security updates and logrotate for /var/log/mongodb/mongod.log.
Performance and Production Tuning
Engine and OS tuning
- Storage engine: WiredTiger (default). Keep data and journal on fast SSDs.
- Cache size: set for tight memory environments.
# /etc/mongod.conf (excerpt)
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 4 # adjust to your RAM and workload
- Open files limits: increase ulimits via systemd override.
sudo systemctl edit mongod
# Editor opens; add:
[Service]
LimitNOFILE=64000
LimitNPROC=32000
sudo systemctl daemon-reload
sudo systemctl restart mongod
- Disable Transparent Huge Pages (THP) and tune NUMA if applicable.
# Temporary (until reboot)
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
# Make persistent via a systemd unit or distro-specific sysfs service
Filesystem and I/O: XFS is recommended; use deadline/none IO schedulers for SSD, and avoid swap pressure (vm.swappiness=1–10).
Schema, indexing, and query design
- Model documents for your access patterns; avoid overly deep arrays.
- Create compound indexes for frequent filters and sorts.
- Use
explain()to confirm index usage; avoid COLLSCAN in hot paths. - Cap hot collections with TTL or archiving if needed.
High availability with replica sets (overview)
Replica sets provide redundancy and automatic failover. Prepare 3+ nodes (primary, two secondaries), unique hostnames, and a keyFile for internal auth.
# Generate and deploy a keyfile to all members
openssl rand -base64 756 | sudo tee /etc/mongo-keyfile >/dev/null
sudo chown mongod:mongod /etc/mongo-keyfile && sudo chmod 600 /etc/mongo-keyfile
# /etc/mongod.conf on all nodes (excerpt)
replication:
replSetName: rs0
security:
keyFile: /etc/mongo-keyfile
# Initialize from one member
mongosh --host primary1 --username siteAdmin --authenticationDatabase admin
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "primary1:27017" },
{ _id: 1, host: "secondary1:27017" },
{ _id: 2, host: "secondary2:27017" }
]
})
Backup and Monitoring
Backups
- Logical:
mongodump/mongorestore(portable, smaller, slower on large datasets). - Snapshots: LVM/ZFS or cloud block storage snapshots (fast, consistent with fsfreeze or journal awareness).
- Test restores regularly; keep off‑server copies and follow 3‑2‑1 backup rule.
Monitoring
- Built‑ins:
mongostat,mongotop,db.serverStatus(). - Metrics: CPU, disk latency (iostat), page faults, connections, replication lag.
- Alerting: set thresholds for slow queries, replication health, disk space, and memory.
mongostat --rowcount 10
mongotop 5
mongosh --quiet --eval "db.serverStatus().connections"
Troubleshooting Common Issues
- Service won’t start: check
/var/log/mongodb/mongod.logfor permission errors on data/log dirs. - Cannot connect remotely: confirm
bindIpincludes server IP and firewall allows your client IP. - Authentication failed: verify
authSource, username, and roles. - High CPU or slow queries: review indexes and
explain(); inspect lock percentage and cache pressure. - Port conflicts: ensure no other service uses 27017; change
net.portif needed. - SELinux denials: check
audit.log; adjust contexts or booleans accordingly.
When Managed Hosting Helps
If you want MongoDB without the sysadmin overhead, a managed VPS or cloud server is ideal. At YouStable, our engineers can provision optimized Linux servers for MongoDB with secure firewalls, automatic backups, monitoring, and 24/7 support—so you focus on your application while we handle uptime, scaling, and security hardening.
FAQs:
Is MongoDB free to use on Linux?
Yes. MongoDB Community Edition is free and open-source under the Server Side Public License (SSPL). It’s suitable for most self‑hosted use cases on Linux servers. MongoDB Enterprise adds advanced security, in‑use encryption, and commercial support.
Which Linux is best for MongoDB—Ubuntu or RHEL?
Both are excellent. Ubuntu offers fast updates and simplicity; RHEL‑family distros provide enterprise stability and SELinux enforcement. Choose the distro your team already manages. Ensure you use the official MongoDB repo for updates.
How do I safely expose MongoDB to the internet?
Prefer private networking or SSH tunnels. If public access is required, enforce TLS, enable authentication, restrict to specific IPs via firewall, and use strong passwords or X.509 authentication. Monitor access logs and enable alerts for failed logins.
How much RAM does MongoDB need?
Small workloads run in 2–4 GB RAM, but 8–16 GB+ is recommended for production. MongoDB benefits from RAM to cache working sets. Tune WiredTiger cache (cacheSizeGB) and watch memory pressure via monitoring.
What’s the difference between mongosh and mongo?
mongosh is the modern MongoDB Shell that replaces the legacy mongo client. It provides improved UX, better error messages, and Node.js integration. Use mongosh for all current versions.