Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › database security

How to Configure a MongoDB Replica Set on Ubuntu (MongoDB 8.0 and Other Supported Releases)

By Freedom251 Team · · 10 min read

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

To configure a MongoDB replica set on Ubuntu, install the same official mongodb-org release on each server, give every member a mutually resolvable hostname, set an identical replication.replSetName and reachable net.bindIp in /etc/mongod.conf, restart all daemons, then run rs.initiate() once from one member. Confirm the election with rs.status() and verify the member list with rs.conf(). The procedure below covers a self-managed deployment and the security decisions that matter before exposing it to a network.

What you need before configuring the replica set

A replica set is a group of MongoDB servers that share a replication configuration and elect one member as the primary. The other members replicate the primary’s data and can participate in a new election if the primary becomes unavailable. This guide assumes you are managing Ubuntu servers yourself rather than using a hosted control plane.

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.

Use separate hosts for production

For a meaningful failure boundary, place members on separate hosts whenever possible. Running every member on one virtual machine does not protect you from that machine, its storage, or its network failing. A simple three-member layout is:

Member Hostname used in MongoDB configuration Example address
Member 0 mongodb0.example.net mongodb0.example.net:27017
Member 1 mongodb1.example.net mongodb1.example.net:27017
Member 2 mongodb2.example.net mongodb2.example.net:27017

Use names that resolve from every member and from clients that must connect. MongoDB recommends hostnames instead of literal IP addresses because address changes otherwise require configuration updates. Starting with MongoDB 5.0, a node configured only with an IP address can fail startup validation, so use resolvable hostnames for MongoDB 5.0 and later.

Match the Ubuntu release, architecture, and MongoDB release

Confirm each server’s Ubuntu release and CPU architecture before installing packages. MongoDB publishes a separate repository procedure for each server release and Ubuntu release. The documented MongoDB 8.0 Ubuntu package path supports 64-bit Ubuntu 24.04 (Noble), 22.04 (Jammy), and 20.04 (Focal). If you choose another MongoDB version, use that version’s repository instructions rather than copying a repository entry from a different release.

  • All members should run the same MongoDB major release and, preferably, the same package update level.
  • All members must use the same replica-set name, although their hostnames are different.
  • Allow each member to reach every other member on the MongoDB port. The examples in this guide use port 27017.
  • Do not expose an unsecured MongoDB listener to a public interface.

Install the official MongoDB packages on every member

Perform the installation steps on each Ubuntu server. The official package is named mongodb-org. Ubuntu also has an unrelated package named mongodb; MongoDB documents that it conflicts with mongodb-org. Remove the unrelated package before installing the official one if it is present.

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

1. Confirm the host and Ubuntu details

Record the hostname that will appear in the replica-set configuration and confirm that it resolves correctly from the other servers. Also confirm that the operating system is a supported 64-bit Ubuntu release for the MongoDB version you selected. Do not mix a repository entry for one Ubuntu codename with a different operating-system release.

2. Configure the version-specific repository

Follow MongoDB’s installation instructions for your selected version and Ubuntu codename. That procedure installs the prerequisites, imports MongoDB’s signing key, creates the matching file under /etc/apt/sources.list.d/, and refreshes APT metadata. The prerequisite command is:

sudo apt-get install -y gnupg curl

After the signing key and repository list are configured, refresh packages and install MongoDB:

sudo apt-get update
sudo apt-get install -y mongodb-org

Repeat the repository and package steps on every member. Installing from the same official release prevents differences in defaults and wire-protocol behavior from complicating an election or a later upgrade.

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

3. Start, enable, and inspect mongod

Start the service and configure it to start after a reboot:

sudo systemctl start mongod
sudo systemctl status mongod
sudo systemctl enable mongod

The default log file is /var/log/mongodb/mongod.log. Inspect it when the service does not start or when a member cannot establish connections. If systemd reports that mongod.service is missing, reload unit files and retry:

sudo systemctl daemon-reload
sudo systemctl start mongod

At this stage a default installation normally listens only on localhost. That is expected; you will change the bind list before attempting to join remote members.

Configure the replica-set identity and network binding

Edit /etc/mongod.conf on every server. The replica-set name must be identical everywhere. The bind list must include localhost and the hostname (or another address) that the other members and clients will use to reach that particular server.

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

Configuration for member 0

replication:
  replSetName: rs0
net:
  bindIp: localhost,mongodb0.example.net

Configuration for member 1

replication:
  replSetName: rs0
net:
  bindIp: localhost,mongodb1.example.net

Configuration for member 2

replication:
  replSetName: rs0
net:
  bindIp: localhost,mongodb2.example.net

Replace the example names with the real, mutually resolvable names. Keep rs0 only if that is the name you intend to use; whatever value you choose must match the _id supplied to rs.initiate(). A typo in one host’s replica-set name prevents it from joining the same set.

MongoDB binds to localhost by default. If localhost is the only entry, remote members cannot connect even when DNS and firewall rules are correct. Conversely, adding a public address without authentication and network restrictions can expose the database. Plan the firewall at the same time as the bind list, allowing the MongoDB port only from trusted member and client networks.

Restart after editing

Restart each daemon after saving its configuration:

sudo systemctl restart mongod
sudo systemctl status mongod

Perform a local service check on every host before initialization. A failed restart usually means a YAML indentation error, an invalid hostname, or an unsupported option; the service status and /var/log/mongodb/mongod.log identify which setting needs correction.

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

Initialize the replica set once

Initialization creates the replica-set configuration and starts an election. Run it from one member only, normally by connecting locally to member 0. MongoDB explicitly requires that rs.initiate() be run on only one mongod instance for the set.

1. Open a local shell

mongosh

Run the command while connected to the local daemon. The shell does not need a remote network path for this first operation, which makes initialization easier to diagnose.

2. Supply one member document per host

rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongodb0.example.net:27017" },
    { _id: 1, host: "mongodb1.example.net:27017" },
    { _id: 2, host: "mongodb2.example.net:27017" }
  ]
})

The top-level _id must equal replication.replSetName in every mongod.conf. Each member’s numeric _id must be unique, and every host must be reachable by every other member. Include the port explicitly, as shown. Do not run a second initialization command on another host after the first command succeeds.

The command returns an acknowledgement and the members begin negotiating an election. The member that wins becomes primary; the others transition into secondary or another reported state while they synchronize. The exact transition timing depends on network and server conditions, so inspect status rather than assuming the election is immediate.

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

Verify health, election, and configuration

After initialization, connect to the elected primary and run both inspection commands:

rs.status()
rs.conf()

Read rs.status() for health

Use rs.status() to identify the current primary and inspect each member’s state and health. Check that all expected members appear, that the primary is elected, and that the other members are reachable rather than reporting an error or a startup state indefinitely. If a member is absent, the problem is usually connectivity, name resolution, a mismatched replica-set name, or a daemon that is not running.

Read rs.conf() for the authoritative member list

rs.conf() shows the replica-set name and the host entries stored in the configuration. Confirm that the name exactly matches the value in every configuration file and that each hostname and port is the address other servers actually use. This catches mistakes such as initializing with an old hostname after changing DNS.

Check from more than one host

A local shell on the primary can succeed even when remote connectivity is broken. Resolve every member hostname from every other member, and verify that firewall policy permits the required MongoDB port in both directions. A replica set is not ready for production until the status view is healthy from the perspective of the whole network, not just one machine.

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.

Secure a networked deployment before adding clients

Replication and network exposure are separate concerns. A working election does not authenticate clients or encrypt member traffic by itself. Before allowing application traffic, restrict firewall sources and configure internal member authentication plus client authorization.

Keyfile authentication for testing and development

MongoDB’s keyfile procedure places the same security.keyFile path in the configuration of every member, alongside the replica-set name and the required bind addresses. An example is:

security:
  keyFile: /etc/mongodb/keyfile
replication:
  replSetName: rs0
net:
  bindIp: localhost,mongodb0.example.net

Copy the same keyfile securely to each host. Apply ownership and restrictive permissions appropriate for the mongod service account; the exact commands depend on the Ubuntu package and service account on the target system, so verify those values locally rather than applying a command blindly. Keep the file inaccessible to unrelated users.

Apply the security configuration on every member, restart all members, and only then initialize the set or reconnect clients. Enabling a keyfile also enforces role-based access control for clients, so applications need database users and roles rather than anonymous access.

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.

MongoDB describes keyfiles as intended for testing and development because their manageability and cryptographic strength are limited. For production, use X.509 certificates or another stronger enterprise authentication approach supported by your security design. Never bind an unauthenticated deployment to a public interface.

Firewall and name-resolution controls

  • Permit the MongoDB port only from the other replica-set members and explicitly approved application or administration networks.
  • Ensure forward and reverse name resolution is reliable enough that each configured hostname identifies the intended server.
  • When an address changes, update DNS and the replica-set host configuration consistently; hostnames reduce, but do not eliminate, change-management work.
  • Keep localhost in net.bindIp when local administration is required, while adding only the reachable name needed for inter-member and client traffic.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot the common failure points

Symptom Likely cause Corrective action
mongod.service not found systemd has not loaded the installed unit. Run sudo systemctl daemon-reload, then start the service again. If it still fails, confirm that mongodb-org installed successfully.
Members cannot join or remain unreachable Localhost-only binding, DNS failure, or a firewall rule blocking the port. Check each host’s net.bindIp, resolve every configured hostname from every member, and allow the required port only between trusted sources.
Initialization reports a configuration mismatch Different replSetName values or an _id that does not match the configuration. Make the value identical in every /etc/mongod.conf and use that exact value as the _id in the single initialization command.
Initialization was attempted on more than one host rs.initiate() was run repeatedly. Stop issuing new initialization commands. Inspect the existing configuration with rs.status() and rs.conf(); if the first attempt failed, read the log and correct the underlying issue before retrying in the appropriate recovery procedure.
MongoDB 5.0 or newer refuses an IP-only setup Nodes are configured only with literal IP addresses. Assign stable, mutually resolvable hostnames and use those names in both net.bindIp and the member host entries.
APT reports package conflicts Ubuntu’s unrelated mongodb package conflicts with mongodb-org. Remove the conflicting package, then install the official package from the version-specific MongoDB repository.
Service fails after editing the YAML file Invalid indentation, a typo, or a hostname that does not resolve. Read sudo systemctl status mongod and /var/log/mongodb/mongod.log, correct the reported setting, and restart the daemon.

Self-managed Ubuntu or a hosted deployment?

A self-managed replica set gives you direct control of operating-system placement, network paths, package timing, firewall policy, and MongoDB configuration. It also makes your team responsible for patching, backups, monitoring, credential management, storage, and failure recovery. A hosted MongoDB option removes local installation and much of the host maintenance, but you accept the provider’s network placement, supported configuration, scaling controls, and service terms.

Decision area Self-managed Ubuntu Hosted MongoDB service
Installation You select Ubuntu hosts, repositories, packages, and service settings. The provider supplies the database environment; there is no local mongod installation.
Operations Your team handles operating-system updates, MongoDB upgrades, backups, firewalling, and incident response. The provider operates the underlying hosts, while you still manage application credentials, data policies, and client configuration.
Network placement You choose subnets, DNS, routing, and latency between members and clients. Placement and available regions or connectivity options depend on the service.
Configuration control You control mongod.conf, hostnames, authentication integration, and firewall rules. You use the provider’s supported settings and controls.
Cost model Costs come from servers, storage, network capacity, operations, and staff time. Charges follow the provider’s service and resource model; local installation work is reduced.

Choose self-management when host-level control and an existing Ubuntu operations practice outweigh the maintenance burden. Choose a hosted service when reducing local database administration is more important than controlling the underlying machines and network layout.

Production-readiness checklist

  • Every member runs the intended, matching MongoDB release from the correct Ubuntu repository.
  • Each server has a stable hostname that resolves from all members and required clients.
  • Every mongod.conf uses the same replication.replSetName.
  • Each net.bindIp includes localhost and the member’s reachable hostname.
  • The firewall permits the MongoDB port only between trusted members and approved clients.
  • mongod starts successfully on every host and is enabled for reboot.
  • rs.initiate() was run once on one member with one host entry per member.
  • rs.status() shows an elected primary and healthy expected members.
  • rs.conf() contains the intended replica-set name, hostnames, and ports.
  • Internal member authentication and client authorization are configured before network exposure.
  • If a keyfile is used, the same securely managed file is present on every member with permissions suitable for the service account; for production, evaluate X.509 or another stronger mechanism.
  • Operators know where to find /var/log/mongodb/mongod.log and how to inspect systemd status during an incident.

Command sequence at a glance

Once DNS, firewall policy, packages, and configuration are ready, the core sequence on a three-member set is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Install the matching official mongodb-org package on all three Ubuntu hosts.
  2. Set the same replSetName and an appropriate per-host bindIp in every /etc/mongod.conf.
  3. Restart and enable mongod on all hosts.
  4. Open mongosh locally on one host and run rs.initiate() with the three fully qualified hostnames and ports.
  5. Connect to the elected primary and run rs.status() and rs.conf().
  6. Apply authentication and restrictive firewall rules before permitting application clients.

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.

database securityLinux administrationMongoDBReplica SetUbuntu

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
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.