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.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
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.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →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.
#1 Best Overall
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.
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.
Recommended Free Tools
Rank #2
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.
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.
Rank #3
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.
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.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesVerify 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.
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:
Best Value
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.
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.bindIpwhen local administration is required, while adding only the reachable name needed for inter-member and client traffic.
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.confuses the samereplication.replSetName. - Each
net.bindIpincludes localhost and the member’s reachable hostname. - The firewall permits the MongoDB port only between trusted members and approved clients.
mongodstarts 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.logand 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:
Quick Recap
- Install the matching official
mongodb-orgpackage on all three Ubuntu hosts. - Set the same
replSetNameand an appropriate per-hostbindIpin every/etc/mongod.conf. - Restart and enable
mongodon all hosts. - Open
mongoshlocally on one host and runrs.initiate()with the three fully qualified hostnames and ports. - Connect to the elected primary and run
rs.status()andrs.conf(). - 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.

