Skip to content

Deploying a MongoDB 7 replica set (PSS, 3-node) on Ubuntu 22.04

Stand up a production-grade MongoDB 7 replica set on Ubuntu 22.04 — keyfile auth, TLS between members, persistent volumes, systemd, and a working failover drill.

You inherited a Mongo deployment that turns out to be a single mongod on a managed VM with a daily filesystem snapshot. The application has been live for two years. The first time the VM reboots for a kernel update during traffic hours, the app errors out for the four minutes mongod takes to come back, the on-call asks “where is the secondary,” and the answer is “there is no secondary.” A replica set is not optional for any production Mongo workload — it’s how the driver discovers a new primary on its own, how rolling maintenance works without downtime, and how you stop relying on snapshot RPO for everyday failures.

What’s happening

A MongoDB replica set is a group of mongod processes that elect a primary and replicate to it via the oplog. The PSS topology — primary + secondary + secondary, three full data-bearing members — is the only configuration that survives a single-node failure cleanly: when the primary dies, the two remaining members hold a majority (2 of 3), elect a new primary in a few seconds, and the driver redirects writes to it. PSA topologies (primary + secondary + arbiter) trade durability for cost and are covered in their own article. PS (two-node) is not a valid production setup — losing either node loses majority, the survivor goes read-only.

Three components have to be wired correctly for a PSS to work in production:

  • Authentication between members. A keyFile (a shared secret) plus TLS certificates so members trust each other and the wire is encrypted. Without these, anyone with network access to port 27017 can join the replica set or read the oplog.
  • Persistent volumes. The data directory must survive instance replacement. Snapshotting the root disk is not a substitute for a separate, mounted data volume.
  • systemd unit with the correct ulimits. Mongo wants nofile=64000 minimum; the default 1024 will tip over under modest load.

How to verify

Once the three nodes are wired, status from any member should look like this:

mongosh --tls --tlsCAFile /etc/mongo/tls/ca.pem \
  --tlsCertificateKeyFile /etc/mongo/tls/client.pem \
  --host mongo01.internal --eval "rs.status()" | jq '.members[] | {name, stateStr, health}'
# [
#   { "name": "mongo01.internal:27017", "stateStr": "PRIMARY",   "health": 1 },
#   { "name": "mongo02.internal:27017", "stateStr": "SECONDARY", "health": 1 },
#   { "name": "mongo03.internal:27017", "stateStr": "SECONDARY", "health": 1 }
# ]

Replication lag from the primary’s oplog:

rs.printSecondaryReplicationInfo()
// source: mongo02.internal:27017
//   syncedTo: <recent timestamp>
//   0 secs behind the primary

Oplog window — how far back in time you can recover from before the oplog rolls:

db.getReplicationInfo()
// { logSizeMB: 51200, usedMB: 7423, timeDiff: 86400, timeDiffHours: 24, ... }

Anything under 12 hours of oplog window for a write-heavy workload is a warning sign — a secondary that falls behind will need a full resync from scratch.

The fix

Save the script as /root/setup-mongo-rs-node.sh and run it on each of the three nodes after editing the NODE_NAME, NODE_IP, and PEER_* variables at the top. It performs the full installer on Ubuntu 22.04: base hardening (UFW, fail2ban, unattended-upgrades, SSH key-only), kernel tuning (transparent hugepages off, vm.swappiness=1, sufficient nofile), the MongoDB 7.0 APT repo, a TLS certificate generation step (self-signed CA + per-node certs — replace with real PKI in production), keyFile generation, mongod.conf with replica-set settings, and a coordinator step that initiates the replica set from mongo01 only.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 MongoDB 7 replica-set (PSS) installer
### Run on each of the 3 nodes after editing the variables below
### After all 3 nodes are up, run the rs.initiate() block from mongo01 only.

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER NODE ===
NODE_NAME="mongo01"                  # mongo01 / mongo02 / mongo03
NODE_IP="10.20.0.11"                 # this node's private IP
PEER_NAMES=("mongo01" "mongo02" "mongo03")
PEER_IPS=("10.20.0.11" "10.20.0.12" "10.20.0.13")
REPLSET_NAME="rs0"
DATA_DEVICE="/dev/sdb"               # dedicated data volume
DATA_MOUNT="/var/lib/mongodb"
ROOT_PASSWORD="CHANGE_ME_ROOT"       # used on coordinator only
# =====================

echo
echo "========================================"
echo "MongoDB replica-set node ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo

echo "==> Refreshing apt and base packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y \
  curl gnupg ca-certificates ufw fail2ban unattended-upgrades \
  chrony tzdata jq lsof tcpdump dnsutils \
  xfsprogs openssl

systemctl enable --now chrony

echo "==> Hostname + hosts file (so members resolve each other)"
hostnamectl set-hostname "${NODE_NAME}.internal"
{
  echo "127.0.0.1 localhost"
  for i in "${!PEER_NAMES[@]}"; do
    echo "${PEER_IPS[$i]} ${PEER_NAMES[$i]}.internal ${PEER_NAMES[$i]}"
  done
} > /etc/hosts

echo "==> SSH hardening"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart ssh

echo "==> fail2ban for sshd"
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port    = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime  = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> Unattended security upgrades"
dpkg-reconfigure -f noninteractive unattended-upgrades

echo "==> UFW (only allow SSH + mongod intra-cluster)"
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
for ip in "${PEER_IPS[@]}"; do
  ufw allow from "${ip}" to any port 27017 proto tcp
done
yes | ufw enable

echo "==> Kernel/sysctl tuning for MongoDB"
cat > /etc/sysctl.d/99-mongodb.conf <<'SYSCTL'
vm.swappiness = 1
vm.dirty_background_ratio = 5
vm.dirty_ratio = 15
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_local_port_range = 10240 65535
fs.file-max = 2097152
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-mongodb.conf <<'LIMITS'
mongodb soft nofile 64000
mongodb hard nofile 64000
mongodb soft nproc 64000
mongodb hard nproc 64000
LIMITS

echo "==> Disable transparent hugepages (MongoDB requirement)"
cat > /etc/systemd/system/disable-thp.service <<'THP'
[Unit]
Description=Disable Transparent Huge Pages (THP)
DefaultDependencies=false
After=sysinit.target local-fs.target
Before=mongod.service

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'echo never | tee /sys/kernel/mm/transparent_hugepage/enabled /sys/kernel/mm/transparent_hugepage/defrag >/dev/null'

[Install]
WantedBy=basic.target
THP
systemctl daemon-reload
systemctl enable --now disable-thp

echo "==> Persistent data volume on ${DATA_DEVICE} (XFS)"
mkdir -p "${DATA_MOUNT}"
if [[ -b "${DATA_DEVICE}" ]] && ! blkid "${DATA_DEVICE}" >/dev/null 2>&1; then
  mkfs.xfs -f -L mongodata "${DATA_DEVICE}"
fi
if blkid "${DATA_DEVICE}" >/dev/null 2>&1; then
  UUID=$(blkid -s UUID -o value "${DATA_DEVICE}")
  if ! grep -q "${UUID}" /etc/fstab; then
    echo "UUID=${UUID} ${DATA_MOUNT} xfs defaults,noatime,nodiratime 0 0" >> /etc/fstab
  fi
  mount -a
fi

echo "==> Adding MongoDB 7.0 apt repository"
install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc \
  | gpg --dearmor -o /etc/apt/keyrings/mongodb-server-7.0.gpg
echo "deb [arch=amd64,arm64 signed-by=/etc/apt/keyrings/mongodb-server-7.0.gpg] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" \
  > /etc/apt/sources.list.d/mongodb-org-7.0.list

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

chown -R mongodb:mongodb "${DATA_MOUNT}"

echo "==> Generating self-signed CA + per-node TLS (replace with real PKI in prod)"
TLS_DIR="/etc/mongo/tls"
mkdir -p "${TLS_DIR}"
chown -R mongodb:mongodb /etc/mongo
chmod 700 "${TLS_DIR}"

# Shared CA must be identical on all 3 nodes — generate on mongo01 and rsync to the others
if [[ "${NODE_NAME}" == "mongo01" ]]; then
  if [[ ! -f "${TLS_DIR}/ca.key" ]]; then
    openssl genrsa -out "${TLS_DIR}/ca.key" 4096
    openssl req -x509 -new -nodes -key "${TLS_DIR}/ca.key" -sha256 -days 3650 \
      -subj "/CN=internal-mongo-ca" -out "${TLS_DIR}/ca.pem"
  fi
fi

# Per-node cert
if [[ -f "${TLS_DIR}/ca.key" ]]; then
  openssl genrsa -out "${TLS_DIR}/${NODE_NAME}.key" 4096
  cat > "${TLS_DIR}/${NODE_NAME}.cnf" <<CNF
[ req ]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no
[ req_distinguished_name ]
CN = ${NODE_NAME}.internal
O  = stackharbor-internal
[ v3_req ]
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = ${NODE_NAME}.internal
DNS.2 = ${NODE_NAME}
IP.1  = ${NODE_IP}
IP.2  = 127.0.0.1
CNF
  openssl req -new -key "${TLS_DIR}/${NODE_NAME}.key" -out "${TLS_DIR}/${NODE_NAME}.csr" \
    -config "${TLS_DIR}/${NODE_NAME}.cnf"
  openssl x509 -req -in "${TLS_DIR}/${NODE_NAME}.csr" \
    -CA "${TLS_DIR}/ca.pem" -CAkey "${TLS_DIR}/ca.key" -CAcreateserial \
    -out "${TLS_DIR}/${NODE_NAME}.crt" -days 365 -sha256 \
    -extensions v3_req -extfile "${TLS_DIR}/${NODE_NAME}.cnf"
  cat "${TLS_DIR}/${NODE_NAME}.crt" "${TLS_DIR}/${NODE_NAME}.key" \
    > "${TLS_DIR}/${NODE_NAME}.pem"
  chmod 600 "${TLS_DIR}/${NODE_NAME}".{key,pem}
fi

echo "==> KeyFile for intra-cluster auth (must be identical on all 3 nodes)"
if [[ "${NODE_NAME}" == "mongo01" ]] && [[ ! -f "${TLS_DIR}/mongo.keyfile" ]]; then
  openssl rand -base64 756 > "${TLS_DIR}/mongo.keyfile"
fi
if [[ -f "${TLS_DIR}/mongo.keyfile" ]]; then
  chmod 400 "${TLS_DIR}/mongo.keyfile"
  chown mongodb:mongodb "${TLS_DIR}/mongo.keyfile"
fi

chown -R mongodb:mongodb /etc/mongo
chmod 600 "${TLS_DIR}"/*.key "${TLS_DIR}"/*.pem 2>/dev/null || true

echo "==> Writing mongod.conf"
cat > /etc/mongod.conf <<EOF
storage:
  dbPath: ${DATA_MOUNT}
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4
      journalCompressor: snappy
    collectionConfig:
      blockCompressor: snappy

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

processManagement:
  fork: false
  timeZoneInfo: /usr/share/zoneinfo

net:
  bindIp: 127.0.0.1,${NODE_IP}
  port: 27017
  tls:
    mode: requireTLS
    certificateKeyFile: ${TLS_DIR}/${NODE_NAME}.pem
    CAFile: ${TLS_DIR}/ca.pem
    allowConnectionsWithoutCertificates: false

security:
  authorization: enabled
  keyFile: ${TLS_DIR}/mongo.keyfile

replication:
  replSetName: ${REPLSET_NAME}
  oplogSizeMB: 51200

operationProfiling:
  slowOpThresholdMs: 200
  mode: slowOp
EOF
chown mongodb:mongodb /etc/mongod.conf
chmod 644 /etc/mongod.conf

mkdir -p /var/log/mongodb
chown mongodb:mongodb /var/log/mongodb

echo "==> systemd drop-in for ulimits"
mkdir -p /etc/systemd/system/mongod.service.d
cat > /etc/systemd/system/mongod.service.d/ulimits.conf <<'UNIT'
[Service]
LimitFSIZE=infinity
LimitCPU=infinity
LimitAS=infinity
LimitNOFILE=64000
LimitNPROC=64000
LimitMEMLOCK=infinity
UNIT

systemctl daemon-reload

echo "==> Reminder — propagate CA + keyFile to peers before starting mongod"
echo "    On mongo01 after CA + keyFile are generated, run:"
echo "    for h in mongo02 mongo03; do"
echo "      rsync -a ${TLS_DIR}/ca.{pem,key} ${TLS_DIR}/mongo.keyfile root@\$h.internal:${TLS_DIR}/"
echo "    done"
echo

if [[ -f "${TLS_DIR}/mongo.keyfile" ]] && [[ -f "${TLS_DIR}/${NODE_NAME}.pem" ]]; then
  echo "==> Enabling and starting mongod"
  systemctl enable --now mongod
else
  echo "==> mongod NOT started — CA + keyFile not present yet on ${NODE_NAME}"
  echo "    Re-run this script after files are in place."
  exit 0
fi

echo "==> Waiting for mongod listener on ${NODE_IP}:27017"
for i in {1..60}; do
  if ss -lntp | grep -q ":27017"; then break; fi
  sleep 2
done

echo
echo "========================================"
echo "DONE on ${NODE_NAME}"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep ":27017" || true
echo
echo "Once all 3 nodes are up, run on mongo01 ONLY:"
cat <<'INIT'

mongosh --tls --tlsCAFile /etc/mongo/tls/ca.pem \
  --tlsCertificateKeyFile /etc/mongo/tls/mongo01.pem \
  --host mongo01.internal <<JS
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongo01.internal:27017", priority: 2 },
    { _id: 1, host: "mongo02.internal:27017", priority: 1 },
    { _id: 2, host: "mongo03.internal:27017", priority: 1 }
  ]
});

// Wait ~5s for primary election, then create the root user
sleep(5000);
db.getSiblingDB("admin").createUser({
  user: "root",
  pwd: "CHANGE_ME_ROOT",
  roles: [{ role: "root", db: "admin" }]
});
JS

INIT

Make it executable and run on each node, mongo01 first so the CA + keyfile are generated:

chmod 700 /root/setup-mongo-rs-node.sh
/root/setup-mongo-rs-node.sh

After mongo01 finishes, copy the shared secrets to the other two, then run the script on mongo02 and mongo03:

# From mongo01
for h in mongo02 mongo03; do
  rsync -a /etc/mongo/tls/ca.{pem,key} /etc/mongo/tls/mongo.keyfile \
    root@${h}.internal:/etc/mongo/tls/
done

Then on mongo02 and mongo03, run their installer. Finally, on mongo01, run the rs.initiate() block from the script’s tail — once it returns, rs.status() should show one PRIMARY and two SECONDARY members on the same configuration version. Do a failover drill before traffic: rs.stepDown(60) from the primary’s shell, and confirm one of the secondaries takes over within a few seconds and the driver’s heartbeat picks it up.

Treat the self-signed CA as a placeholder. In production, issue per-node certs from a real internal CA (your existing PKI, HashiCorp Vault’s PKI engine, or step-ca) with a 90-day rotation and an automated renewal. Snapshot the data volume hourly during business hours; the replica set protects you from a node failure, snapshots protect you from a logical-corruption or “wrong UPDATE without a WHERE” event that replicates instantly.

To run a Mongo replica set without owning the runbook, our Cloud Compute team operates it under Managed Cloud Ops with replication-lag and oplog-window alerts on our monitoring plane — or start a scoping call if you’d like us to take it over.