Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Cloud Infrastructure

How to Create a Sharded MongoDB Cluster on an Ubuntu VPS

By Freedom251 Team · · 12 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To build a MongoDB sharded cluster on Ubuntu VPS instances, deploy replica sets for the config servers and each shard, then place one or more mongos routers in front of them. A production topology uses three config-server members and three members per shard replica set; a smaller single-shard arrangement is suitable only for development or testing. The reliable sequence is to prepare private DNS and firewalls, install the same MongoDB release everywhere, secure inter-node authentication, initialize the config and shard replica sets, start mongos, add the shards, and then choose a shard key from measured workload patterns.

What a sharded MongoDB cluster contains

MongoDB describes three essential components: shards, mongos routing processes, and config servers. Together they divide data across replica sets while keeping routing metadata available to clients.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Component Purpose How it is deployed
Shard Stores a subset of database data and serves reads and writes for its ranges or hash partitions. Each shard is a replica set with its own name, members, elections and storage.
Config-server replica set Stores cluster metadata such as databases, collections, chunks and shard placement. Use a dedicated replica set named in the configDB connection string.
mongos Acts as the client-facing query router, locating the relevant shard and returning results. Run one or more stateless routers; applications connect to these routers rather than directly to shard members.

MongoDB 8.0 also documents a config-shard arrangement, but the conventional design for a new VPS deployment is a separate config-server replica set. Keep config-server and shard roles explicit so that an outage or maintenance event is easier to reason about.

Choose the VPS topology before installing anything

Development or test layout

A minimal test environment can contain one mongos, one shard replica set and one config-server replica set. You may run several processes on fewer VPS instances to reduce cost, but co-location removes failure isolation and should not carry production traffic.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Production reference layout

MongoDB’s production reference topology uses three members in the config-server replica set and three members in each shard replica set, plus one or more mongos routers. Place members across at least three data centers or availability zones when feasible. This lets a single host or zone fail without immediately losing replica-set voting power.

Design Typical processes Use Main trade-off
Single-shard test One config replica set, one shard replica set, one router Application development, migration rehearsals and functional testing Little or no fault isolation; not a production failure-tolerant design
Small production start Three config members, three members for the first shard, redundant routers Production workloads that currently need one shard Higher VPS, storage and network cost before adding more shards
Multi-shard production Three config members, three members per shard, multiple routers Data sets or write rates that require horizontal partitioning More elections, balancing, monitoring and shard-key consequences

Count voting members, not just VPS instances. A single VPS can host multiple processes for a lab, but placing all members of a replica set on one machine defeats redundancy. Geographic distribution also increases latency, so measure the round-trip time between zones before selecting replica-set members.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prerequisites for Ubuntu VPS nodes

  • Use a supported 64-bit Ubuntu LTS image. MongoDB 8.0 documents Ubuntu 20.04 (Focal), 22.04 (Jammy) and 24.04 (Noble) on x86_64, with selected ARM64 support. Use one architecture and one MongoDB major version across the cluster.
  • Assign stable DNS names such as cfg1.db.internal, cfg2.db.internal, cfg3.db.internal, sh1a.db.internal and router1.db.internal. Use those names in replica-set and sharded-cluster configuration instead of changing raw addresses.
  • Provide private inter-node connectivity. Do not make database listeners reachable from the public internet. Allow only the application networks, administration network and the specific cluster peers that need to connect.
  • Synchronize clocks with the VPS provider’s time service or another trusted NTP source. Clock drift complicates TLS, elections, logs and incident timelines.
  • Choose storage with predictable IOPS and enough free space for data, indexes, journal activity, backups and temporary balancing work. Sharding does not remove the need to monitor disk pressure on every member.
  • Plan backups before loading production data, including a copy of config-server data and a tested restore procedure.

Install the same MongoDB release on every node

Run the installation steps on all config-server, shard and router hosts. Do not mix major releases in the initial deployment.

  1. Install the repository prerequisites:
sudo apt-get update
sudo apt-get install -y gnupg curl
  1. Import the MongoDB 8.0 signing key and create the MongoDB 8.0 APT source file for the node’s Ubuntu codename. Use the official MongoDB installation instructions for the exact key command and repository stanza matching Noble, Jammy or Focal; do not reuse a repository line for a different Ubuntu release.
  2. Refresh package metadata and install the server packages:
sudo apt-get update
sudo apt-get install -y mongodb-org
  1. Check the installed version on each host:
mongod --version
mongos --version
mongosh --version

When reproducibility matters, pin the package version after validating it in a staging cluster and record the selected MongoDB release. Review the current MongoDB release documentation before a production rollout because package names, supported Ubuntu releases and security defaults can change.

Build the private network and baseline firewall

MongoDB processes bind to localhost by default. That safe default means a new node cannot join a remote replica set until you explicitly add approved hostnames or private addresses to net.bindIp.

  • Permit each config-server member to reach the other config members on the configured config-server port.
  • Permit each shard member to reach the other members of its own shard replica set.
  • Permit every mongos router to reach all config and shard members.
  • Permit application clients to reach routers, not shard or config-server listeners.
  • Permit SSH or administration access only from a management network, and log denied traffic.

Apply host firewalls and, where available, the VPS provider’s network firewall. Create DNS records before starting MongoDB, then verify forward and reverse resolution from every participating host. If a hostname resolves to a public address, correct the DNS or routing plan before binding MongoDB to it.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Secure internal and client authentication

Secure the cluster before exposing any listener beyond localhost. MongoDB’s guidance is explicit: before binding an instance to a publicly accessible address, protect the cluster from unauthorized access.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Keyfile bootstrap for a lab

A keyfile is simple for development and testing. Generate one file, copy it securely to every mongod and mongos host, and make it readable only by the MongoDB service account:

openssl rand -base64 756 | sudo tee /etc/mongodb-keyfile > /dev/null
sudo chown mongodb:mongodb /etc/mongodb-keyfile
sudo chmod 400 /etc/mongodb-keyfile

The bytes and permissions must match on every node. Keyfiles have limited manageability and cryptographic strength, so MongoDB positions them mainly for testing and development.

Production authentication

For production, plan TLS with X.509 certificates, LDAP proxy authentication or Kerberos as appropriate for your identity infrastructure. Use internal authentication on every mongod and mongos, and use role-based access control for application users. For intra-cluster SCRAM on MongoDB 5.3 and later, use SCRAM-SHA-256.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Bootstrap the first administrative user through the localhost exception on an isolated node, then enable authorization and internal authentication consistently across the deployment. Create separate users for administrators, monitoring and applications; never share the administrator credential with application code.

Configure and initialize the config-server replica set

Use a distinct replica-set name, such as cfgRS, and set the config-server role on every member. The following example uses three hostnames and port 27019; use the same values in DNS, firewall rules and service configuration.

Config-server YAML

On each config host, create or edit /etc/mongod.conf. Change the hostname and, if necessary, the data path for that host.

storage:
  dbPath: /var/lib/mongodb
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
net:
  port: 27019
  bindIp: 127.0.0.1,cfg1.db.internal
replication:
  replSetName: cfgRS
sharding:
  clusterRole: configsvr
security:
  keyFile: /etc/mongodb-keyfile
  authorization: enabled

On cfg2 and cfg3, replace the second bindIp value with that host’s name. If you are using TLS or X.509, add the TLS settings required by your certificate design instead of relying on a keyfile.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Start the members and initiate the set

  1. Validate ownership and permissions of the data, log and key files, then start MongoDB:
sudo systemctl enable --now mongod
sudo systemctl status mongod
  1. Connect locally to one config member with mongosh and initiate the set. The configsvr option must be true:
mongosh --host cfg1.db.internal --port 27019
rs.initiate({
  _id: 'cfgRS',
  configsvr: true,
  members: [
    { _id: 0, host: 'cfg1.db.internal:27019' },
    { _id: 1, host: 'cfg2.db.internal:27019' },
    { _id: 2, host: 'cfg3.db.internal:27019' }
  ]
})
  1. Wait for a primary and secondaries, then inspect the result:
rs.status()
rs.conf()

A production config-server replica set requires at least three members. Back up its data before maintenance because the config database contains the metadata that lets routers find chunks and shards.

Configure each shard replica set

Every shard has its own unique replica-set name. For example, the first shard can be shard01RS with members sh1a.db.internal, sh1b.db.internal and sh1c.db.internal. A second shard would use a different name and its own members.

Shard-member YAML

On each shard host, use a configuration like this, changing the hostname and replica-set name for each shard:

storage:
  dbPath: /var/lib/mongodb
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
net:
  port: 27017
  bindIp: 127.0.0.1,sh1a.db.internal
replication:
  replSetName: shard01RS
sharding:
  clusterRole: shardsvr
security:
  keyFile: /etc/mongodb-keyfile
  authorization: enabled

Start all members and check the service logs for binding, authentication or storage errors:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo systemctl enable --now mongod
sudo systemctl status mongod
sudo journalctl -u mongod --since '10 minutes ago'

Initiate the shard set

Connect to one member and initiate the replica set with all members:

mongosh --host sh1a.db.internal --port 27017
rs.initiate({
  _id: 'shard01RS',
  members: [
    { _id: 0, host: 'sh1a.db.internal:27017' },
    { _id: 1, host: 'sh1b.db.internal:27017' },
    { _id: 2, host: 'sh1c.db.internal:27017' }
  ]
})

Run rs.status() and wait until one member is PRIMARY and the others are SECONDARY with healthy replication. Repeat the process for every additional shard, using a new replica-set name and member list each time.

Start redundant mongos routers

mongos is stateless: it reads metadata from the config-server replica set and routes operations to shards. Run at least two routers when application availability requires a router to survive maintenance or failure. Put them behind your existing load balancer or provide a client-side list of router addresses.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Create /etc/mongos.conf on each router host:

sharding:
  configDB: cfgRS/cfg1.db.internal:27019,cfg2.db.internal:27019,cfg3.db.internal:27019
net:
  port: 27017
  bindIp: 127.0.0.1,router1.db.internal
security:
  keyFile: /etc/mongodb-keyfile
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongos.log

Start the router using the distribution’s mongos service or an explicitly managed service unit:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo systemctl enable --now mongos
sudo systemctl status mongos

Do not configure a data dbPath for mongos. Confirm that the router can authenticate to all config and shard members before allowing application traffic.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Add shards and verify the cluster

Connect the shell to a router, not directly to a shard, for cluster administration:

mongosh --host router1.db.internal --port 27017

Add each shard with its replica-set connection string:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sh.addShard('shard01RS/sh1a.db.internal:27017,sh1b.db.internal:27017,sh1c.db.internal:27017')

Check the registered shards and cluster state:

sh.listShards()
sh.status()

sh.listShards() should show the replica-set name and members you supplied. If a shard remains unavailable, inspect DNS resolution, firewall counters, keyfile or certificate permissions, and the replica-set state on the shard itself.

Enable sharding and select a shard key from workload evidence

Adding shards does not automatically distribute every collection. Enable sharding for the target database, then shard individual collections:

sh.enableSharding('appdb')
sh.shardCollection('appdb.events', { tenantId: 'hashed' })

The command above is only an example. A hashed key may distribute writes well, but it can be a poor choice for range queries that need neighboring values. Select the actual key after examining query and write patterns.

  • Query targeting: Frequent operations should include the shard key so mongos can target a subset of shards instead of broadcasting.
  • Cardinality: The key needs enough distinct values to create useful partitions. A low-cardinality field can leave data concentrated on a few shards.
  • Write distribution: Avoid a monotonically increasing key when inserts would all arrive at the newest chunk and create a hot shard.
  • Range behavior: Choose a range-friendly key when range scans are central to the workload; choose hashing only when even distribution matters more than locality.
  • Document availability: Verify that the key exists, is stable for the document’s lifetime and is present in the operations that matter.
  • Uniqueness is not enough: A unique field can still produce poor distribution or scatter-gather queries. Do not choose it solely because it is unique.

Measure representative queries before and after sharding. Watch the profiler and application metrics for scatter-gather operations, uneven chunk sizes and shard-specific write pressure.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validate failover before production traffic

Replica-set elections

During a maintenance rehearsal, stop or isolate a primary and confirm that an eligible secondary is elected, clients reconnect and replication catches up. Record election duration and application errors; a successful election does not guarantee that every driver handles the interruption correctly.

Router redundancy

Remove one mongos endpoint from the load balancer or client list. Existing connections may fail, but new connections should use a surviving router and continue to reach the cluster.

Config-server protection

If a config-server primary cannot be elected, cluster metadata becomes read-only and chunk migrations or splits stop. If all config servers are unavailable, the cluster can become inoperable. Test restoration of config-server backups and document the exact maintenance order.

Network and security checks

  • From every permitted peer, verify DNS, TCP reachability and TLS or keyfile authentication.
  • From an unapproved network, verify that database ports are blocked.
  • Confirm that application credentials have only their required roles.
  • Check that logs do not contain credentials and that keyfiles or private keys are not world-readable.

Operate and monitor the cluster

  • Replication: Track replication lag, member state, elections and optime progress for every config and shard replica set.
  • Storage: Alert on disk pressure, journal capacity, IOPS saturation and rapidly growing indexes.
  • Balancing: Watch chunk balancing, migration failures and uneven shard utilization after collections are sharded.
  • Routers: Monitor mongos connectivity, connection pools, request latency and stale-metadata warnings.
  • Backups: Back up shard data and the config database, retain copies outside the VPS failure domain and perform restore drills.
  • Change control: Keep MongoDB versions, configuration files, replica-set names, DNS records and firewall rules in an auditable inventory.

Plan upgrades and maintenance one replica-set member at a time, preserving voting availability. Never delete or recreate config-server data casually: it is cluster metadata, not merely another copy of application documents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting common setup failures

A member cannot join the replica set

Check that the hostname in rs.conf() resolves from every member, the advertised port is allowed by both host and provider firewalls, and net.bindIp includes the hostname or private address. Confirm that all members use the same replica-set name and authentication material.

mongos reports stale or unavailable metadata

Check the health of every config-server member first. Then inspect router logs and connectivity to each config-server hostname. Do not add or remove shards while the config-server replica set is unhealthy.

Authentication works locally but fails between hosts

Verify that the keyfile bytes, owner and mode are identical on all hosts, or that every certificate has the expected subject, trust chain and hostname coverage. Ensure internal authentication settings are consistent on every mongod and mongos.

One shard receives most writes

Inspect the shard key, chunk distribution and query patterns. A low-cardinality or monotonic key can create a hot shard even when additional capacity exists. Re-evaluate the key with measured workload data rather than adding routers and expecting them to fix data skew.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Production readiness checklist

  • All nodes run the same supported MongoDB major version and a supported 64-bit Ubuntu LTS release.
  • Config-server and shard members use stable private DNS names and distinct replica-set names.
  • Production replica sets have three voting members distributed across failure domains where feasible.
  • Only required peer, router and administration traffic passes the firewalls.
  • Internal authentication and client authorization are enabled consistently; production identity uses TLS/X.509, LDAP or Kerberos where appropriate.
  • At least two routers are available when the application requires router-level availability.
  • Config-server and shard backups have been restored successfully in a separate environment.
  • Election, router-failover, network-isolation and disk-pressure tests have documented outcomes.
  • The shard key is justified by cardinality, distribution, range behavior and query targeting—not uniqueness alone.
  • Monitoring covers replication lag, elections, disk pressure, balancing, router connectivity and stale metadata.

The Bottom Line

A dependable Ubuntu VPS deployment is built in layers: private DNS and firewalls first, identical MongoDB packages second, authenticated config and shard replica sets third, and redundant mongos routers last. Keep the three-member production topology, protect config-server metadata, and select the shard key from real workload measurements before directing application traffic.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Cloud InfrastructureDatabase ShardingDevOpsMongoDBUbuntuVPS

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.