To configure MongoDB on a Linux server, install the official MongoDB repository, install mongod, start and enable the service, set bindIp and security.authorization in mongod.conf, create an admin user via mongosh, open firewall rules, and enable TLS. Finally, tune Linux limits and storage for WiredTiger performance and set up backups and monitoring.
In this step-by-step guide, you’ll learn exactly how to configure MongoDB on a Linux server for production in 2026. We’ll cover installation on Ubuntu/Debian and RHEL-based systems, secure configuration, performance tuning, replica sets, backups, monitoring, and common fixes. The instructions are beginner-friendly but rooted in real-world ops experience.
Search Intent and What You’ll Learn
This tutorial targets users searching for “how to configure MongoDB on Linux server,” including admins deploying new instances, developers moving to production, and teams hardening existing installs. You’ll get actionable commands, proven defaults, and context to make informed choices for Ubuntu, Debian, and RHEL-based distributions.
Prerequisites and System Requirements
- Linux server (Ubuntu 22.04/24.04, Debian 12, RHEL/AlmaLinux/Rocky 8 or 9)
- 64-bit CPU, 2+ cores (4+ recommended), 4 GB RAM minimum (8–32 GB for production)
- Root or sudo access
- Open ports: 27017/TCP (MongoDB), 27018/27019 if sharding or replication
- Time synchronized (chrony or systemd-timesyncd) to avoid auth and replication drift
- Primary keyword focus: How to Configure MongoDB on Linux Server (plus secondary: MongoDB installation, MongoDB configuration, security hardening, performance tuning)
Step 1: Add the Official MongoDB Repository
Ubuntu 22.04/24.04 (Jammy/Noble) and Debian 12 (Bookworm)
Replace the codename with your distro if needed. The example uses MongoDB 7.0 (a widely deployed stable series). Always verify the latest supported series from the official docs.
# Ubuntu Jammy example (22.04). For Noble (24.04), replace 'jammy' with 'noble'
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
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-get update
# Debian 12 (Bookworm) example
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
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-get update
RHEL 8/9, AlmaLinux, Rocky Linux
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 clean all
Step 2: Install MongoDB Server
# Ubuntu/Debian
sudo apt-get install -y mongodb-org
# RHEL/Alma/Rocky
sudo dnf install -y mongodb-org
This installs mongod, mongosh, and related tools. Keep your OS and MongoDB branch aligned with your support policy.
Step 3: Start and Enable the Service
sudo systemctl enable --now mongod
sudo systemctl status mongod --no-pager
journalctl -u mongod -b --no-pager | tail -n 50
If mongod fails to start, check data path permissions, SELinux context, or port conflicts on 27017.
Step 4: Base Configuration (mongod.conf)
On most distributions, the config lives at /etc/mongod.conf. Set network binding, data/log paths, and enable authorization. Always back up this file before editing.
Recommended Production Defaults
sudo cp /etc/mongod.conf /etc/mongod.conf.bak.$(date +%F)
sudo tee /etc/mongod.conf >/dev/null <<'EOF'
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
wiredTiger:
engineConfig:
# Set later based on RAM; omit to auto-calc
# cacheSizeGB: 8
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27017
bindIp: 127.0.0.1,10.0.0.10 # replace 10.0.0.10 with your server's private IP
processManagement:
timeZoneInfo: /usr/share/zoneinfo
security:
authorization: enabled
# replication:
# replSetName: rs0 # uncomment when configuring a replica set
# net:
# tls:
# mode: requireTLS
# certificateKeyFile: /etc/ssl/mongo/mongo.pem
EOF
sudo systemctl restart mongod
By default, bind to localhost and a private IP (never 0.0.0.0 in production). We’ll enable TLS and replication later.
Step 5: Create the First Admin User
With authorization enabled, create an admin user in the admin database. Use SCRAM-SHA-256 and a strong password.
mongosh --host 127.0.0.1 --port 27017
use admin
db.createUser({
user: "siteAdmin",
pwd: passwordPrompt(),
roles: [ { role: "root", db: "admin" } ]
})
exit
Reconnect using authentication:
mongosh --username siteAdmin --authenticationDatabase admin --host 127.0.0.1
Step 6: Open Firewall Ports Safely
Ubuntu/Debian (UFW)
# Allow only trusted subnets or peers (replace CIDR)
sudo ufw allow from 10.0.0.0/24 to any port 27017 proto tcp
sudo ufw reload
sudo ufw status
RHEL/Alma/Rocky (firewalld)
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/24" port protocol="tcp" port="27017" accept'
sudo firewall-cmd --reload
sudo firewall-cmd --list-all
Never expose 27017 to the public internet. Use private networks, VPN, or security groups.
Step 7: Enable TLS/SSL Encryption
Encrypt traffic in transit. Use an internal CA or Let’s Encrypt certificate. Here’s a quick self-signed example for lab use; for production, use a real CA-signed cert.
sudo mkdir -p /etc/ssl/mongo
sudo openssl req -newkey rsa:4096 -x509 -days 825 -nodes \
-keyout /etc/ssl/mongo/mongo.key \
-out /etc/ssl/mongo/mongo.crt \
-subj "/CN=mongo.internal.example.com"
sudo sh -c 'cat /etc/ssl/mongo/mongo.key /etc/ssl/mongo/mongo.crt > /etc/ssl/mongo/mongo.pem'
sudo chmod 600 /etc/ssl/mongo/mongo.pem
sudo chown mongod:mongod /etc/ssl/mongo/mongo.pem
sudo tee -a /etc/mongod.conf >/dev/null <<'EOF'
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/mongo/mongo.pem
EOF
sudo systemctl restart mongod
Connect with TLS from clients by specifying SSL parameters in drivers or mongosh (for self-signed certs, provide CA file or allow invalid certs only in test environments).
Step 8: Linux and WiredTiger Performance Tuning
Increase File Descriptors and Processes
sudo tee /etc/security/limits.d/mongodb.conf >/dev/null <<'EOF'
mongod soft nofile 64000
mongod hard nofile 64000
mongod soft nproc 32000
mongod hard nproc 32000
EOF
Reboot or ensure PAM limits are applied to the mongod service. Confirm via lsof and cat /proc/$(pidof mongod)/limits.
Disable Transparent Huge Pages (THP) and Tune Swappiness
# THP often hurts latency-sensitive databases
sudo tee /etc/systemd/system/disable-thp.service >/dev/null <<'EOF'
[Unit]
Description=Disable Transparent Huge Pages (THP)
After=network.target
[Service]
Type=simple
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled; echo never > /sys/kernel/mm/transparent_hugepage/defrag'
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now disable-thp
# Lower swappiness
echo 'vm.swappiness=1' | sudo tee /etc/sysctl.d/99-mongo.conf
sudo sysctl --system
Right-size WiredTiger Cache
WiredTiger cache defaults to a fraction of RAM. In memory-constrained environments or when running on shared nodes, set cacheSizeGB in mongod.conf to avoid OS pressure. Example: 50%–60% of RAM on dedicated DB servers.
Step 9: Configure a Replica Set (High Availability)
Replica sets provide redundancy and failover. Set a name and restart before initiating.
# In /etc/mongod.conf
replication:
replSetName: rs0
sudo systemctl restart mongod
# On the primary node
mongosh --username siteAdmin --authenticationDatabase admin
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo1.internal:27017" },
{ _id: 1, host: "mongo2.internal:27017" },
{ _id: 2, host: "mongo3.internal:27017", arbiterOnly: false }
]
})
rs.status()
Ensure all members can resolve and reach each other on 27017. Use private DNS or /etc/hosts entries and consistent TLS settings.
Step 10: Backups and Point-in-Time Recovery
Combine logical backups with filesystem snapshots or cloud-native snapshots for safety. For busy clusters, consider hot backups or backup agents.
# Logical backup
mongodump --authenticationDatabase admin -u siteAdmin -h 127.0.0.1 \
--archive=/backups/mongo-$(date +%F).archive --gzip
# Restore
mongorestore --archive=/backups/mongo-YYYY-MM-DD.archive --gzip
For LVM or cloud volume snapshots, quiesce writes if possible or use replica secondaries for safer snapshots. Always test restores.
Step 11: Monitoring, Logs, and Maintenance
- Real-time tools: mongostat, mongotop
- System metrics: node exporter, CloudWatch, or your monitoring stack
- MongoDB exporter for Prometheus, Grafana dashboards
- Log rotation: use logAppend true; trigger with sudo kill -SIGUSR1 $(pidof mongod)
- Alert on replication lag, cache pressure, slow queries, disk I/O, and OOM events
SELinux and Data Directory Moves
If you change dbPath to a custom mount (e.g., /data/mongo) on RHEL-based systems with SELinux enforcing, set the correct contexts or mongod will fail to read/write.
# Example: moving data to /data/mongo
sudo systemctl stop mongod
sudo rsync -aHAX /var/lib/mongo/ /data/mongo/
sudo semanage fcontext -a -t mongod_var_lib_t "/data/mongo(/.*)?"
sudo restorecon -Rv /data/mongo
sudo sed -i 's|dbPath: .*|dbPath: /data/mongo|' /etc/mongod.conf
sudo systemctl start mongod
Troubleshooting Quick Wins
- Port already in use: sudo ss -lntp | grep 27017
- Permission denied on data path: check ownership (mongod:mongod) and SELinux contexts
- Auth errors: confirm db, user, and role; check keyfile/clusterAuthMode in replicas
- Connection refused from remote: verify bindIp, firewall, and TLS settings
- High CPU or memory: review slow queries, add indexes, adjust WiredTiger cache, and verify THP is disabled
When Managed Hosting Makes Sense
If you’d rather focus on your app than kernel flags and backups, consider managed MongoDB on optimized VPS or cloud instances. At YouStable, we provide NVMe-backed servers, private networking, proactive monitoring, and optional managed database services—ideal for teams that want performance, security, and predictable costs without the ops burden.
Summary: Your Production-Ready MongoDB Checklist
- Install from the official MongoDB repository
- Start and enable mongod via systemd
- Set bindIp, enable authorization, and create an admin user
- Lock down the firewall and require TLS
- Tune limits, THP, swappiness, and WiredTiger cache
- Use replica sets for HA and validated backups for DR
- Monitor health, capacity, and query performance
FAQs: How to Configure MongoDB on Linux Server
Which Linux distro is best for MongoDB in 2026?
Ubuntu LTS (22.04/24.04) and RHEL-compatible distros (AlmaLinux/Rocky 8/9) are top choices due to stability, long-term updates, and first-class MongoDB repository support. Choose the one your team already manages well to simplify patching and automation.
How do I secure MongoDB if it must be internet-accessible?
Use a VPN or bastion first. If exposure is unavoidable, enforce TLS (requireTLS), strong auth, firewall allow-lists, rate limiting at a reverse proxy, and continuous monitoring. Never bind to 0.0.0.0 without strict network controls and alerts.
What port does MongoDB use and can I change it?
MongoDB listens on TCP 27017 by default. Change it in mongod.conf under net.port, adjust your firewall rules, and update client connection strings. Port changes add obscurity, not security; use TLS and proper authentication regardless.
How much RAM should I allocate to MongoDB?
Start with at least 8 GB for production. Aim for RAM close to your working set. Set WiredTiger cache to ~50–60% of RAM on dedicated DB servers. Monitor page faults, cache pressure, and query latency to iterate safely.
How do I move the MongoDB data directory to a new disk?
Stop mongod, rsync data to the new path, update storage.dbPath in mongod.conf, fix ownership and SELinux contexts, then start mongod. Validate data, logs, and performance after the move. For replicas, move secondaries first to preserve availability.
With these steps, you now know how to configure MongoDB on a Linux server—from installation and security to tuning and HA. If you need a hardened, high-performance stack with expert support, YouStable can help you deploy MongoDB the right way.