To set up MongoDB on a Linux server, add MongoDB’s official repository to your distro, install the mongodb-org package, start and enable the mongod service, secure it with authentication, configure bindIp and firewall rules, and verify connections with mongosh. The steps below cover Ubuntu/Debian and RHEL/AlmaLinux/Rocky/Amazon Linux with production-ready settings.
In this guide, you’ll learn how to setup MongoDB on Linux server from scratch—covering installation, configuration, security, performance tuning, backups, and troubleshooting. I’ll share practical, battle‑tested advice based on 12+ years supporting databases on VPS, cloud, and bare-metal servers, so beginners can follow along confidently.
What You’ll Learn
- Install MongoDB using the official repository on Ubuntu/Debian and RHEL-based distros
- Start, enable, and verify the mongod service
- Configure bindIp, ports, TLS/SSL, and authentication
- Secure the server firewall (UFW/firewalld) and handle SELinux
- Apply production best practices (THP, ulimits, file system)
- Back up and restore with mongodump/mongorestore
- Monitor performance and fix common errors
Prerequisites and Planning
- Linux: Ubuntu 22.04 LTS (Jammy), Ubuntu 20.04 (Focal), Debian 11 (Bullseye), RHEL 8/9, AlmaLinux/Rocky 8/9, or Amazon Linux 2
- Root or sudo access
- 2+ CPU cores, 4–8 GB RAM minimum for small workloads (more for production)
- Disk: SSD recommended; file system XFS preferred for WiredTiger
- Open ports: 27017/TCP (MongoDB) restricted to trusted IPs only
- Time synchronized (systemd-timesyncd or chrony)
Note: MongoDB supports specific distro versions per release line. Check the official docs if your OS differs. This guide demonstrates commonly deployed, supported combinations.
Quick Install Cheat‑Sheet by Distro
Ubuntu 22.04 (Jammy) – MongoDB 8.0 Example
sudo apt-get update
sudo apt-get install -y curl gnupg
# Import MongoDB GPG key
curl -fsSL https://pgp.mongodb.com/server-8.0.asc | \
sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg
# Add official repo
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/8.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
# Install
sudo apt-get update
sudo apt-get install -y mongodb-org
# Start and enable
sudo systemctl enable --now mongod
# Check status and logs
systemctl status mongod --no-pager
sudo journalctl -u mongod -e --no-pager
If you’re on Ubuntu 20.04 (Focal) or a newer LTS, replace “jammy” with your codename and “8.0” with the latest stable line supported by MongoDB for your OS.
Debian 11 (Bullseye) – MongoDB 7.0 Example
sudo apt-get update
sudo apt-get install -y curl gnupg
curl -fsSL 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 bullseye/mongodb-org/7.0 main" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
sudo systemctl enable --now mongod
Debian support varies by MongoDB version. Use the latest supported server line for your Debian release from MongoDB’s official docs.
RHEL 8/9, AlmaLinux 8/9, Rocky 8/9 – MongoDB 8.0 Example
sudo tee /etc/yum.repos.d/mongodb-org-8.0.repo >/dev/null <<'EOF'
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/8.0/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-8.0.asc
EOF
sudo dnf clean all
sudo dnf -y install mongodb-org
sudo systemctl enable --now mongod
sudo systemctl status mongod --no-pager
Amazon Linux 2 – MongoDB 7.0 Example
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/amazon/2/mongodb-org/7.0/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-7.0.asc
EOF
sudo yum clean all
sudo yum -y install mongodb-org
sudo systemctl enable --now mongod
Why not use the distro’s default mongodb package? It’s often outdated. The official mongodb-org repository provides current, security-patched releases.
Initial Verification
# Confirm mongod is running
sudo systemctl status mongod --no-pager
# Connect with MongoDB Shell (mongosh)
mongosh --host 127.0.0.1 --port 27017
# Check server build info
db.runCommand({ buildInfo: 1 })
Secure Configuration (Critical for Production)
Edit mongod.conf to restrict network exposure and enable authentication. On most distros, the file is at /etc/mongod.conf.
sudo nano /etc/mongod.conf
Recommended baseline:
# /etc/mongod.conf
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
net:
port: 27017
bindIp: 127.0.0.1,10.0.0.5 # Replace 10.0.0.5 with your private server IP
security:
authorization: enabled
processManagement:
timeZoneInfo: /usr/share/zoneinfo
setParameter:
diagnosticDataCollectionEnabled: true
TLS/SSL (strongly recommended for remote clients):
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/mongodb.pem # PEM with cert + key
CAFile: /etc/ssl/ca.pem
Restart to apply changes:
sudo systemctl restart mongod
Create the First Admin User
If you just enabled authorization, first ensure you can still connect locally. Create an admin in the admin database, then use that account going forward.
mongosh --host 127.0.0.1 --port 27017
use admin
db.createUser({
user: "siteAdmin",
pwd: passwordPrompt(),
roles: [ { role: "root", db: "admin" } ]
})
exit
Create an app-specific user with limited privileges:
mongosh --host 127.0.0.1 --port 27017 -u siteAdmin -p --authenticationDatabase admin
use myapp
db.createUser({
user: "myappUser",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "myapp" } ]
})
exit
Firewall and SELinux
UFW (Ubuntu/Debian)
# Allow only your trusted IP(s)
sudo ufw allow from 203.0.113.10 to any port 27017 proto tcp
# Or allow internal VPC subnet
sudo ufw allow from 10.0.0.0/24 to any port 27017 proto tcp
sudo ufw reload
firewalld (RHEL/Alma/Rocky/Amazon)
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" \
source address="203.0.113.10" port protocol="tcp" port="27017" accept'
sudo firewall-cmd --reload
SELinux: default port 27017 works without changes. If you change the port, label it:
sudo semanage port -a -t mongod_port_t -p tcp 27018
sudo systemctl restart mongod
Performance and Production Best Practices
- File system: Prefer XFS on SSD; avoid ext4 for heavy OLTP workloads.
- Disable Transparent Huge Pages (THP) and NUMA for predictable latency.
- Set ulimits: allow higher open files and processes.
- Memory: WiredTiger cache uses ~50% of RAM by default; ensure headroom.
- Swap: Keep minimal but not zero; set vm.swappiness=1–10.
- Backups and monitoring from day one (see sections below).
Disable THP (temporary, until reboot)
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
Persist THP settings via systemd or rc.local according to your distro’s best practice.
ULimits (example)
echo "mongod soft nofile 64000
mongod hard nofile 64000" | sudo tee /etc/security/limits.d/99-mongodb.conf
Backups and Restores
Logical backups work everywhere; filesystem snapshots are faster for large datasets. Always test restores.
mongodump / mongorestore
# Backup all databases
mongodump --username siteAdmin --password --authenticationDatabase admin \
--out /backups/mongo-$(date +%F)
# Restore a specific database
mongorestore --username siteAdmin --password --authenticationDatabase admin \
--db myapp /backups/mongo-2025-01-10/myapp
LVM/Cloud Snapshots (hot backup pattern)
- Ensure journaling is enabled (default).
- fsfreeze the volume, snapshot, then thaw; or use cloud volume snapshots.
- Keep oplog entries (in replica sets) to cover snapshot time.
Monitoring and Observability
- Logs: /var/log/mongodb/mongod.log (journalctl -u mongod -f)
- mongostat and mongotop for quick health checks
- Enable slow query profiling for tuning
# Quick metrics
mongostat --rowcount 5
mongotop 5
# Enable slow query profiling (level 1)
mongosh -u siteAdmin -p --authenticationDatabase admin --eval \
'db.setProfilingLevel(1, { slowms: 100 })'
Optional: Basic Replica Set Initialization
For high availability, run three nodes and initiate a replica set. Use private networking and TLS with keyfiles or x.509 auth.
# In /etc/mongod.conf on each node
replication:
replSetName: rs0
# Then on the primary candidate
mongosh -u siteAdmin -p --authenticationDatabase admin --host 10.0.0.5
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "10.0.0.5:27017" },
{ _id: 1, host: "10.0.0.6:27017" },
{ _id: 2, host: "10.0.0.7:27017" }
]
})
rs.status()
Troubleshooting Common Errors
- Port already in use: Another process bound to 27017. Run sudo lsof -i :27017 and stop/disable the conflicting service or change MongoDB port consistently across config, firewall, and SELinux.
- Failed to connect: Check bindIp (must include your client’s IP or 0.0.0.0 for testing only), firewall rules, and TLS settings.
- Permission denied on dbPath: Ensure mongod owns /var/lib/mongo and /var/log/mongodb; run sudo chown -R mongod:mongod <path>.
- Authentication failed: Confirm the correct auth database (usually admin) and user role. Try mongosh -u user -p –authenticationDatabase admin.
- High I/O or slow queries: Review indexes (db.collection.getIndexes()), enable slow-query profiling, and confirm THP is disabled.
Real-World Tips from Hosting Experience
- Keep MongoDB and OS security patches current via the official repo.
- Separate data volume (e.g., /var/lib/mongo on dedicated SSD) to simplify snapshotting and scaling.
- Use private networking between app and DB; never expose 27017 to the public internet.
- Test restores quarterly; a backup you haven’t restored is a hope, not a plan.
- For steady growth, schedule compactions/maintenance during low-traffic windows.
Don’t want to manage all this yourself? YouStable’s managed VPS and cloud servers can provision MongoDB with hardened defaults, offsite backups, and 24×7 monitoring—so you focus on shipping features, not tuning THP and firewall rules.
With these steps, you now know how to setup MongoDB on Linux server the right way—from installation and security to performance and maintenance. If you prefer a managed path, YouStable can deploy and maintain a production-grade MongoDB stack tailored to your workload.
FAQs: How to Setup MongoDB on Linux Server
What’s the safest way to install MongoDB on Linux?
Use MongoDB’s official repository (mongodb-org) for your distro, install with your native package manager, and avoid community packages that lag behind. This ensures current features, security patches, and a proper systemd service.
How do I secure MongoDB after installation?
Enable authorization in mongod.conf, create an admin user, restrict bindIp to private addresses, enforce TLS/SSL, and allow port 27017 only from trusted IPs. Keep the OS and MongoDB updated and audit logs regularly.
Which port does MongoDB use and should I change it?
Default is 27017/TCP. You can change it, but the real security comes from firewalling, TLS, and auth. If you do change the port, update firewall and (if applicable) SELinux labels accordingly.
How can I back up MongoDB on a live server?
Use mongodump for logical backups or take filesystem/LVM/cloud snapshots with journaling enabled. For large datasets, snapshots are faster; ensure oplog coverage in replica sets and always validate restores.
Do I need a replica set for production?
For high availability and point-in-time recovery with the oplog, yes. A three-node replica set is the standard approach. Start single-node in development; move to replica sets before production traffic scales.