Skip to main contentSkip to navigation
[email protected]
Client AreaSupport
Hosting Mammoth
HostingMammothYour Data, Our Responsibility
Home
Solutions
Hosting Services
Store
Pricing
About
Blog
API
Contact

Stay Ahead of the Curve

Get the latest insights on cybersecurity, AI innovations, and enterprise data solutions delivered to your inbox.

Hosting Mammoth
HostingMammothEnterprise Solutions

Enterprise-grade data solutions. Hosting, recovery, cybersecurity, and AI-powered services for businesses worldwide.

[email protected]
Sun - Fri, 9:00am - 5:00pm

Services

  • Cloud Hosting
  • Data Recovery
  • Cybersecurity
  • Legal Support
  • MSP Services
  • Web Development
  • AI Services
  • Free Server Migration

Hosting

  • VPS Hosting (NVMe SSD)
  • VDS Hosting (NVMe)
  • Storage VPS (High SSD)
  • GPU Servers
  • Managed Services
  • Cloud Firewall
  • Load Balancer
  • One-Click Apps
  • n8n Hosting
  • Object Storage
  • FAQ

Company

  • Store
  • Pricing
  • About Us
  • Locations
  • Blog
  • Testimonials
  • Contact
  • Affiliate Program
  • White-Label
  • Terms of Service
  • Privacy Policy
  • Browser Cookies
  • SLA

Support

  • Client Area
  • Submit Ticket
  • Knowledge Base
  • Server Status
  • API Documentation

© 2026 Hosting Mammoth. All rights reserved.

Knowledge Base
Getting StartedAccount ManagementVPS HostingGPU ServersStorage VPSCloud FirewallLoad BalancerServer ManagementBilling & PaymentsSupport & TicketsAffiliate ProgramReseller ProgramMarketplace & Appsn8n HostingManaged ServicesServer MigrationAPI & DevelopersSecurityTroubleshootingGlossaryInstall Guides
  1. Home
  2. /
  3. Support
  4. /
  5. Install Guides
  6. /
  7. How To Install Mongodb Ubuntu
GUIDEInstall Guides

How to Install MongoDB on Ubuntu 24.04 - Self-Hosted Document Database

23 min read

How to Install MongoDB on Ubuntu 24.04 - Self-Hosted Document Database

MongoDB is the most widely deployed document database in the world, backing everything from e-commerce catalogs to real-time analytics pipelines and mobile app backends. While MongoDB Atlas makes getting started trivial, running your own mongod on a VPS gives you dramatically lower costs at scale, complete data sovereignty, and the freedom to tune every knob. This guide walks you through a production-grade MongoDB 7.0 Community Edition install on Ubuntu 24.04, from apt repository setup to TLS x.509 client authentication.

Want a bigger plan? Document databases love RAM. Our Professional VPS ships with 16 GB of RAM, 8 vCPU, and 200 GB NVMe - plenty of headroom for WiredTiger's cache and a growing working set.

Table of Contents

  • What is MongoDB?
  • Why Self-Host MongoDB Instead of Atlas?
  • Prerequisites
  • Step 1: Update the System
  • Step 2: Add the MongoDB 7.0 apt Repository
  • Step 3: Install mongodb-org
  • Step 4: Disable Transparent Huge Pages via tuned
  • Step 5: Configure mongod.conf
  • Step 6: Start mongod and Create the Admin User
  • Step 7: Initialize a Replica Set
  • Step 8: Back Up with mongodump
  • Step 9: Enable TLS with x.509 Client Authentication
  • Atlas Compatibility and Migration
  • Troubleshooting
  • FAQ
  • Related Guides
  • What is MongoDB?

    MongoDB is an open-source, distributed document database that stores data as flexible, JSON-like BSON documents. Unlike relational databases that force every row in a table into the same rigid schema, MongoDB collections can hold documents with varying fields, nested arrays, and deeply embedded sub-documents. This makes it particularly well suited to application data that evolves over time, user-generated content with optional fields, product catalogs with wildly different attributes per category, and log or event streams.

    MongoDB 7.0 is the current major release line and introduced queryable encryption, approximate percentile aggregation operators, compound wildcard indexes, and significantly faster initial sync for new replica set members. Under the hood, every modern MongoDB deployment uses the WiredTiger storage engine, which provides document-level concurrency control, snappy/zstd compression, and a configurable in-memory cache that is the single most important performance knob you will tune.

    The product ecosystem has three tiers: Community Edition (what we install in this guide), Enterprise Advanced (adds LDAP, Kerberos, in-memory engine, encrypted storage engine, auditing), and MongoDB Atlas (the fully managed cloud service). The wire protocol, query language, drivers, and core features are identical across all three, which means applications written for Atlas port cleanly to a self-hosted Community install.

    Why Self-Host MongoDB Instead of Atlas?

    MongoDB Atlas is a phenomenal product for getting started, but the economics flip hard as you scale. Here is why teams move to self-hosted MongoDB on a VPS:

    • Cost at scale - Atlas M30 dedicated clusters start around $210/month for 8 GB RAM / 40 GB disk. A comparable VPS with 16 GB RAM and 200 GB NVMe runs roughly $25-40/month. Once your working set crosses 50 GB, the Atlas bill grows linearly while a VPS is fixed. For bootstrapped SaaS and cost-sensitive workloads, the savings compound quickly.
    • Data sovereignty and compliance - Self-hosting in a known EU, UK, or US data center simplifies GDPR, HIPAA, and UK-GDPR compliance. You choose the exact jurisdiction, network path, and backup location. No cross-border replication surprises.
    • No egress fees - Atlas bills for data transferred out of the cluster. On a VPS with unmetered or generous bandwidth, high-traffic reads and analytics queries cost nothing extra.
    • Full version and extension freedom - Run any MongoDB major version, mix in Ops Manager, Percona Backup for MongoDB, or community tooling that Atlas does not allow.
    • Kernel and filesystem tuning - Atlas abstracts away the OS. On your own VPS you can pick XFS, tune swappiness, disable transparent huge pages, and right-size the WiredTiger cache for your specific workload.
    • Predictable capacity planning - Atlas auto-scales at a price. A VPS gives you a fixed monthly cost and the ability to upgrade on your own schedule.
    The trade-off is operational ownership: you are responsible for patching, backups, monitoring, and failover. For teams comfortable managing Linux, that trade is usually well worth the 70-85% cost reduction.

    Cost Comparison: MongoDB Atlas vs. Self-Hosted

    ScenarioAtlas M30Atlas M40Self-Hosted VPS
    RAM8 GB16 GB16 GB
    Storage40 GB80 GB200 GB NVMe
    Monthly cost~$210~$420~$29
    Egress feesYesYesNone (unmetered)
    Backup retentionExtra costExtra costIncluded in your ops
    Version pinningLimitedLimitedAny 7.0.x

    Prerequisites

    Before you begin, make sure you have:

    • A VPS running Ubuntu 24.04 LTS with root or sudo access
    • SSH access to your server
    • At least 8 GB of RAM (16 GB+ recommended for production)
    • At least 50 GB of free disk space on the data volume
    • An open firewall for the port you will bind mongod to (default 27017) - restricted to your application servers only
    Recommended Plan: Professional VPS
    >
    MongoDB performs best when the working set fits in RAM. The Professional plan gives you:
    >
    - 8 vCPU cores
    - 16 GB RAM
    - 200 GB NVMe SSD
    - Unmetered bandwidth
    >
    This gives WiredTiger a healthy cache and plenty of storage headroom for logs, oplog, backups, and indexes.

    Connect to your server via SSH:

    bash
    ssh root@your-server-ip

    Step 1: Update the System

    Start by updating your package index and installing a few prerequisites. MongoDB's repository signing key requires gnupg and curl.

    bash
    sudo apt update && sudo apt upgrade -y
    sudo apt install -y gnupg curl ca-certificates

    If the kernel was upgraded, reboot:

    bash
    sudo reboot

    Step 2: Add the MongoDB 7.0 apt Repository

    Ubuntu's default universe repository does not contain mongodb-org. You must add MongoDB Inc.'s official apt repository to get current, supported builds. At the time of writing, MongoDB 7.0 does not publish a dedicated noble (24.04) distribution entry, so we use the jammy (22.04) repository, which is the pattern MongoDB recommends in their official docs until the 24.04 line ships.

    Import the MongoDB 7.0 GPG key:

    bash
    curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
      sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor

    Add the repository definition:

    bash
    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

    Refresh the package index so apt picks up the new repo:

    bash
    sudo apt update

    You should see a line like:

    text
    Get:5 https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 InRelease

    Step 3: Install mongodb-org

    The mongodb-org meta-package installs all four MongoDB server components in one go:

    • mongodb-org-server - the mongod daemon
    • mongodb-org-mongos - the sharded cluster query router
    • mongodb-org-shell - the legacy mongo shell (deprecated, but still useful)
    • mongodb-org-tools - mongodump, mongorestore, mongoexport, mongoimport, mongotop, mongostat
    Install:

    bash
    sudo apt install -y mongodb-org

    Install the modern mongosh shell separately (it is the replacement for the legacy mongo CLI):

    bash
    sudo apt install -y mongodb-mongosh

    Verify:

    bash
    mongod --version
    mongosh --version

    Expected output (versions will vary):

    text
    db version v7.0.14
    Build Info: { ... }
    text
    2.3.2

    Pin the package versions to prevent accidental major upgrades via apt upgrade:

    bash
    echo "mongodb-org hold" | sudo dpkg --set-selections
    echo "mongodb-org-database hold" | sudo dpkg --set-selections
    echo "mongodb-org-server hold" | sudo dpkg --set-selections
    echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
    echo "mongodb-org-tools hold" | sudo dpkg --set-selections

    Step 4: Disable Transparent Huge Pages via tuned

    Transparent Huge Pages (THP) is a Linux kernel feature that transparently backs process memory with 2 MB pages instead of 4 KB. For most workloads this is a win, but WiredTiger explicitly recommends disabling THP because it triggers latency spikes during compaction and increases memory fragmentation on write-heavy workloads. The official MongoDB production notes call this out as one of the most common performance problems on Linux.

    The cleanest way to disable THP on Ubuntu 24.04 is a dedicated tuned profile that survives reboots and upgrades.

    Install tuned:

    bash
    sudo apt install -y tuned
    sudo systemctl enable --now tuned

    Create a profile directory:

    bash
    sudo mkdir -p /etc/tuned/no-thp-mongodb

    Write the profile:

    bash
    sudo tee /etc/tuned/no-thp-mongodb/tuned.conf > /dev/null <<'EOF'
    [main]
    summary=Disable transparent hugepages for MongoDB WiredTiger
    include=virtual-guest

    [vm] transparent_hugepages=never

    [sysctl] vm.swappiness=1 vm.dirty_ratio=15 vm.dirty_background_ratio=5 EOF

    Activate it:

    bash
    sudo tuned-adm profile no-thp-mongodb

    Verify THP is off:

    bash
    cat /sys/kernel/mm/transparent_hugepage/enabled
    cat /sys/kernel/mm/transparent_hugepage/defrag

    Both should report [never] inside the brackets:

    text
    always madvise [never]
    always defer defer+madvise madvise [never] never

    The profile also lowers vm.swappiness to 1 (MongoDB hates swap) and tunes dirty-page thresholds to smooth out write bursts.

    Step 5: Configure mongod.conf

    The default /etc/mongod.conf is a safe starting point but needs three changes for production: cache sizing, bind address, and authorization.

    Open the file:

    bash
    sudo nano /etc/mongod.conf

    Replace its contents with:

    yaml
    storage:
      dbPath: /var/lib/mongodb
      engine: wiredTiger
      wiredTiger:
        engineConfig:
          cacheSizeGB: 8
          journalCompressor: snappy
        collectionConfig:
          blockCompressor: snappy
        indexConfig:
          prefixCompression: true

    systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log

    net: port: 27017 bindIp: 127.0.0.1,10.0.0.5 maxIncomingConnections: 2000

    processManagement: timeZoneInfo: /usr/share/zoneinfo

    security: authorization: enabled

    replication: replSetName: rs0 oplogSizeMB: 2048

    operationProfiling: slowOpThresholdMs: 100 mode: slowOp

    Key settings explained:

    • wiredTiger.engineConfig.cacheSizeGB: 8 - The single biggest performance knob. WiredTiger's internal cache holds uncompressed documents and indexes. MongoDB defaults to max(50% of RAM - 1 GB, 256 MB). On a 16 GB VPS, set this to 8 explicitly so the OS retains 8 GB for the filesystem page cache, mongod's own overhead, and other services. Never size the cache to all available RAM.
    • net.bindIp: 127.0.0.1,10.0.0.5 - By default, mongod binds only to 127.0.0.1, which is safe but blocks remote app servers. Add your private network IP (replace 10.0.0.5 with your VPS's private IP). Never bind to 0.0.0.0 on a public interface without a firewall - unauthenticated internet-exposed MongoDB instances are the canonical ransomware target.
    • security.authorization: enabled - Forces clients to authenticate. We will create the admin user in the next step using the localhost exception.
    • replication.replSetName: rs0 - Puts mongod into replica set mode, which is required for transactions, change streams, and point-in-time recovery. More on this in Step 7.
    • replication.oplogSizeMB: 2048 - A 2 GB oplog gives you roughly 24+ hours of replay window for most small-to-mid workloads. Increase for write-heavy workloads.
    • operationProfiling.slowOpThresholdMs: 100 - Logs any query over 100 ms for later analysis.
    Save and exit.

    Enable and start the service:

    bash
    sudo systemctl enable --now mongod
    sudo systemctl status mongod

    Expected output:

    text
    mongod.service - MongoDB Database Server
         Loaded: loaded (/lib/systemd/system/mongod.service; enabled; preset: enabled)
         Active: active (running) since Thu 2026-04-16 10:00:00 UTC; 3s ago

    If it fails, check the log:

    bash
    sudo tail -n 50 /var/log/mongodb/mongod.log

    Step 6: Start mongod and Create the Admin User

    With authorization: enabled, you need at least one user before you can do anything else. MongoDB provides a localhost exception: before any user exists, you can connect from 127.0.0.1 without credentials and create the first user.

    Connect with mongosh:

    bash
    mongosh --host 127.0.0.1 --port 27017

    Switch to the admin database and create a root user:

    javascript
    use admin

    db.createUser({ user: "mongoadmin", pwd: passwordPrompt(), roles: [ { role: "userAdminAnyDatabase", db: "admin" }, { role: "dbAdminAnyDatabase", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" }, { role: "clusterAdmin", db: "admin" } ] })

    passwordPrompt() will prompt you interactively so the password never lands in shell history.

    Exit mongosh:

    javascript
    exit

    From now on you must authenticate:

    bash
    mongosh --host 127.0.0.1 --port 27017 -u mongoadmin -p --authenticationDatabase admin

    Create an Application User

    Never use the root admin for application traffic. Create a per-application user scoped to one database:

    javascript
    use myapp

    db.createUser({ user: "myapp_user", pwd: passwordPrompt(), roles: [ { role: "readWrite", db: "myapp" } ] })

    Your application connects with this user via a connection string like:

    text
    mongodb://myapp_user:[email protected]:27017/myapp?authSource=myapp&replicaSet=rs0

    Step 7: Initialize a Replica Set

    Even on a single server, running a replica set unlocks three features you almost certainly want: multi-document transactions, change streams (for reactive apps and CDC), and point-in-time recovery via oplog replay.

    You already set replSetName: rs0 in mongod.conf. Now initialize the replica set.

    Connect as the admin user:

    bash
    mongosh -u mongoadmin -p --authenticationDatabase admin

    Run:

    javascript
    rs.initiate({
      _id: "rs0",
      members: [
        { _id: 0, host: "mongo.example.com:27017", priority: 1 }
      ]
    })

    Replace mongo.example.com:27017 with the hostname (or private IP) your application will use to connect. This value is baked into the replica set configuration - do not use 127.0.0.1 unless no external client will ever connect.

    Check the status:

    javascript
    rs.status()

    You should see "stateStr" : "PRIMARY" within a few seconds. The prompt will also change to rs0 [primary]>.

    Adding Secondary Members Later

    When you are ready to add a second server for HA, install mongod on it using the same procedure, then from the primary run:

    javascript
    rs.add("mongo2.example.com:27017")

    MongoDB will perform an initial sync (copy all data) and then replicate ongoing writes via the oplog. For production HA you want at least three members (primary + secondary + arbiter or three data-bearing members) so elections can reach quorum.

    Step 8: Back Up with mongodump

    mongodump produces a logical backup as compressed BSON files you can restore to any MongoDB instance of the same or newer major version.

    Create a backup directory:

    bash
    sudo mkdir -p /var/backups/mongodb
    sudo chown mongodb:mongodb /var/backups/mongodb

    Run a one-off backup:

    bash
    mongodump \
      --host "rs0/mongo.example.com:27017" \
      --username mongoadmin \
      --password "YOUR_PASSWORD" \
      --authenticationDatabase admin \
      --archive=/var/backups/mongodb/mongo-$(date +%F).archive \
      --gzip

    Key flags:

    • --archive=FILE writes a single compact archive rather than a directory tree
    • --gzip compresses the archive (typically 3-5x smaller)
    • --host "rs0/..." uses replica-set-aware connection so the dump prefers a secondary

    Schedule Nightly Backups

    Create a wrapper script at /usr/local/bin/mongo-backup.sh:

    bash
    sudo tee /usr/local/bin/mongo-backup.sh > /dev/null <<'EOF'
    #!/bin/bash
    set -euo pipefail

    BACKUP_DIR="/var/backups/mongodb" RETENTION_DAYS=14 TIMESTAMP=$(date +%F-%H%M) ARCHIVE="${BACKUP_DIR}/mongo-${TIMESTAMP}.archive.gz"

    mongodump \ --host "rs0/localhost:27017" \ --username "$MONGO_BACKUP_USER" \ --password "$MONGO_BACKUP_PASS" \ --authenticationDatabase admin \ --archive="$ARCHIVE" \ --gzip

    find "$BACKUP_DIR" -name "mongo-*.archive.gz" -mtime +${RETENTION_DAYS} -delete EOF

    sudo chmod +x /usr/local/bin/mongo-backup.sh

    Store credentials in /etc/default/mongo-backup (mode 0600, owned by root):

    text
    MONGO_BACKUP_USER=backup_user
    MONGO_BACKUP_PASS=your-backup-password

    Add a systemd timer or cron entry:

    bash
    sudo crontab -e
    text
    0 3   * . /etc/default/mongo-backup && /usr/local/bin/mongo-backup.sh >> /var/log/mongo-backup.log 2>&1

    Restoring

    bash
    mongorestore \
      --host "rs0/mongo.example.com:27017" \
      --username mongoadmin --password "PASSWORD" --authenticationDatabase admin \
      --archive=/var/backups/mongodb/mongo-2026-04-16.archive.gz \
      --gzip \
      --drop

    Step 9: Enable TLS with x.509 Client Authentication

    Binding MongoDB to a private network is a good start. For any connection crossing an untrusted network, enable TLS. x.509 client authentication goes one step further by using client certificates in place of passwords - the gold standard for service-to-service MongoDB auth.

    Generate a Certificate Authority and Server Cert

    This example uses a self-signed CA; for internet-exposed deployments use Let's Encrypt or your internal PKI.

    bash
    sudo mkdir -p /etc/mongo-tls && cd /etc/mongo-tls

    Create the CA

    sudo openssl genrsa -out mongo-ca.key 4096 sudo openssl req -new -x509 -days 3650 -key mongo-ca.key -out mongo-ca.crt \ -subj "/C=US/ST=CA/O=MyOrg/OU=MongoDB/CN=MongoCA"

    Create the server cert

    sudo openssl genrsa -out mongo-server.key 4096 sudo openssl req -new -key mongo-server.key -out mongo-server.csr \ -subj "/C=US/ST=CA/O=MyOrg/OU=MongoDB/CN=mongo.example.com" sudo openssl x509 -req -in mongo-server.csr -CA mongo-ca.crt -CAkey mongo-ca.key \ -CAcreateserial -out mongo-server.crt -days 825 -sha256

    MongoDB wants a combined PEM

    sudo bash -c 'cat mongo-server.key mongo-server.crt > mongo-server.pem' sudo chown mongodb:mongodb /etc/mongo-tls/* sudo chmod 600 /etc/mongo-tls/.key /etc/mongo-tls/.pem

    Update mongod.conf

    Add a net.tls block:

    yaml
    net:
      port: 27017
      bindIp: 127.0.0.1,10.0.0.5
      tls:
        mode: requireTLS
        certificateKeyFile: /etc/mongo-tls/mongo-server.pem
        CAFile: /etc/mongo-tls/mongo-ca.crt
        allowConnectionsWithoutCertificates: false

    Restart:

    bash
    sudo systemctl restart mongod

    Create an x.509 Client

    Generate a client cert with a distinguished Common Name:

    bash
    sudo openssl genrsa -out /etc/mongo-tls/client-myapp.key 4096
    sudo openssl req -new -key /etc/mongo-tls/client-myapp.key -out /etc/mongo-tls/client-myapp.csr \
      -subj "/C=US/ST=CA/O=MyOrg/OU=Apps/CN=myapp.client"
    sudo openssl x509 -req -in /etc/mongo-tls/client-myapp.csr -CA /etc/mongo-tls/mongo-ca.crt \
      -CAkey /etc/mongo-tls/mongo-ca.key -CAcreateserial \
      -out /etc/mongo-tls/client-myapp.crt -days 365 -sha256

    sudo bash -c 'cat /etc/mongo-tls/client-myapp.key /etc/mongo-tls/client-myapp.crt > /etc/mongo-tls/client-myapp.pem'

    In mongosh, register the subject as a MongoDB user:

    javascript
    use $external

    db.createUser({ user: "CN=myapp.client,OU=Apps,O=MyOrg,ST=CA,C=US", roles: [ { role: "readWrite", db: "myapp" } ] })

    The user field must match the certificate's subject exactly, in MongoDB's RFC 2253 format.

    Connect with the Client Cert

    bash
    mongosh \
      --host mongo.example.com \
      --tls \
      --tlsCAFile /etc/mongo-tls/mongo-ca.crt \
      --tlsCertificateKeyFile /etc/mongo-tls/client-myapp.pem \
      --authenticationMechanism MONGODB-X509 \
      --authenticationDatabase '$external'

    No password required - authentication is bound to possession of the client key.

    Atlas Compatibility and Migration

    The mongod you just installed speaks the same wire protocol as MongoDB Atlas, and drivers are interchangeable. A Node.js app pointed at Atlas today can switch to your self-hosted replica set by changing only the connection string:

    Atlas:

    text
    mongodb+srv://user:[email protected]/myapp?retryWrites=true&w=majority

    Self-hosted:

    text
    mongodb://user:[email protected]:27017/myapp?replicaSet=rs0&retryWrites=true&w=majority

    Migrating from Atlas

    For a one-time migration:

    bash
    # Dump from Atlas
    mongodump --uri "mongodb+srv://user:[email protected]/myapp" \
      --archive=atlas-dump.archive --gzip

    Restore into your self-hosted cluster

    mongorestore --host "rs0/mongo.example.com:27017" \ -u mongoadmin -p --authenticationDatabase admin \ --archive=atlas-dump.archive --gzip

    For zero-downtime migration, use MongoDB Cluster-to-Cluster Sync (mongosync), which performs an initial load and then tails change streams until cutover. Alternatively, roll your own CDC with change streams and an application-level dual-writer.

    If MongoDB's schema flexibility is overkill for your use case, consider the relational alternatives in our PostgreSQL install guide or the distributed-SQL option in our CockroachDB install guide. For teams who want a managed alternative that is not Atlas, our MongoDB Atlas alternatives comparison breaks down the trade-offs.

    Troubleshooting

    ProblemCauseSolution
    mongod fails to start, log shows Failed to unlink socket fileStale socket from previous crashsudo rm -f /tmp/mongodb-27017.sock && sudo systemctl start mongod
    MongoServerError: Authentication failedWrong --authenticationDatabaseAdmin users always authenticate against admin; app users against their own DB
    Slow queries, high page faultsWorking set exceeds WiredTiger cacheIncrease cacheSizeGB, add indexes, or scale RAM
    WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always' in logsTHP still enabledRe-apply the no-thp-mongodb tuned profile and reboot
    not master and slaveOk=false errorsApp connected to secondary without read preferenceSet driver read preference to primary or use rs0/host1,host2,host3 URI
    Replica set stuck in STARTUP2 foreverClock skew between membersInstall chrony on all members and verify chronyc tracking
    MongoServerSelectionError: connect ECONNREFUSED from app serverFirewall or bindIpConfirm bindIp includes the private IP and ufw allow from APP_IP to any port 27017

    Viewing Logs

    bash
    sudo tail -f /var/log/mongodb/mongod.log

    Useful JSON log filters:

    bash
    sudo grep '"s":"E"' /var/log/mongodb/mongod.log | tail -n 50      # errors only
    sudo grep '"c":"COMMAND"' /var/log/mongodb/mongod.log | tail -n 20 # slow ops

    FAQ

    Why self-host MongoDB instead of using MongoDB Atlas?

    Self-hosting on a VPS typically costs 70-85% less than Atlas at moderate scale (50+ GB working set). You retain full data sovereignty, avoid per-GB storage surcharges, egress fees, and backup add-ons, and can run any MongoDB version or extension without platform restrictions. The trade-off is operational ownership - you handle patching, monitoring, and failover yourself.

    What RAM does a self-hosted MongoDB server need?

    WiredTiger's internal cache defaults to 50% of RAM minus 1 GB. For production, size RAM so your working set (hot documents plus indexes) fits comfortably in cache. 16 GB is a sane starting point for most small-to-mid workloads; scale to 32-64 GB for heavier indexes. Monitor wiredTiger.cache.bytes currently in cache and pages read into cache metrics - if the cache is full and read rates stay high, you are under-provisioned.

    Is MongoDB Community Edition compatible with Atlas drivers?

    Yes. MongoDB Atlas runs the same mongod binary and wire protocol as Community Edition. Any driver that speaks to Atlas (Node.js, Python, Go, Java, C#, Ruby) connects to a self-hosted 7.0 server with only a connection string change. Features like change streams, transactions, aggregation pipelines, and index types behave identically across Atlas and self-hosted. The only differences are Atlas-exclusive features (Atlas Search, Atlas Vector Search, Data Federation) which rely on separate managed components.

    Do I need a replica set for a single-server deployment?

    Yes, even single-node. A replica set is required for change streams (reactive apps, CDC pipelines), multi-document transactions, and causal consistency. It also unlocks point-in-time recovery via the oplog and lets you later add members without downtime. The overhead of running a single-member replica set versus a standalone is negligible - a few MB of oplog and one extra thread.

    How do I back up a self-hosted MongoDB?

    mongodump produces logical BSON backups you can restore with mongorestore. For production, schedule nightly mongodump runs to compressed archives with 14-30 day retention, and for larger clusters add a second tier of physical snapshots via the cloud provider's block-storage snapshot feature. For point-in-time recovery, retain the oplog for a window longer than your backup interval and use mongorestore --oplogReplay. Test restores quarterly - an untested backup is a Schrödinger backup.

    Does Ubuntu 24.04 ship MongoDB in its default repos?

    No. Ubuntu's universe repository does not include mongodb-org. You must add the official MongoDB apt repository (repo.mongodb.org) to get current 7.0 builds with security updates. At the time of writing, MongoDB Inc. publishes packages keyed to jammy (22.04) that install cleanly on noble (24.04) - this is the pattern documented in the official MongoDB install guide and is what we use above.

    Can I migrate from MongoDB Atlas to a self-hosted VPS?

    Yes. Use mongodump against your Atlas cluster (SRV URI with credentials), then mongorestore into your self-hosted replica set. For zero-downtime migration, run a MongoDB Cluster-to-Cluster Sync (mongosync) which performs an initial load followed by change stream replication until you cut over. Applications need only a connection string change. Expect data transfer from Atlas to incur egress charges on Atlas's side - factor that into migration timing.

    Related Guides

    • MongoDB Atlas Alternatives: Self-Hosted and Managed Options Compared
    • How to Install PostgreSQL on Ubuntu 24.04
    • How to Install CockroachDB on Ubuntu 24.04
    • Official MongoDB documentation: mongodb.com/docs

    Ready to self-host MongoDB?
    >
    Our Professional VPS gives you 16 GB RAM, 8 vCPU, and 200 GB NVMe - exactly the spec this guide is tuned for. Deploy in 60 seconds, follow this guide, and your production-grade MongoDB 7.0 replica set is live before lunch.
    >
    Get a Professional VPS - Unmetered bandwidth, EU/US/UK data centers.

    Was this article helpful?

    ← Back to Install GuidesBrowse all categories →

    Still have questions?

    Contact Support →Submit a Ticket