Skip to content

Deploying a MongoDB 7 sharded cluster (3 config + 2 shards x PSS) on AlmaLinux 9

Stand up a horizontally scaled MongoDB 7 deployment on AlmaLinux 9 — 3-node config server replica set, two shard replica sets (PSS), mongos routers, with keyfile auth.

Your workload outgrew vertical scaling. The single replica set sits at 70% wiredTiger cache pressure on the largest VM your provider offers, the working set no longer fits in RAM on the primary, and the queries that used to be quick are doing disk I/O on every page touch. Vertical is exhausted; the data has to be partitioned across multiple replica sets. That’s a sharded cluster — three distinct topologies running together, all of which have to be configured before you put a single document in.

What’s happening

A MongoDB sharded cluster is three concentric tiers:

  • Config server replica set (CSRS). A 3-node replica set that stores cluster metadata — which shard owns which chunk of data, which mongos routers exist, balancer state. Lose majority on CSRS and the whole cluster stops accepting writes routed by chunk key. This is the most fragile tier; treat it as a tier-0 dependency.
  • Shard replica sets. Each shard is its own PSS replica set. A two-shard cluster has six data-bearing mongod processes plus the config tier. You add shards as workload grows; you do not start with one shard and “add another later” — start with two minimum so the chunk-migration path is exercised from day one.
  • mongos routers. Stateless query routers that read the config metadata and dispatch operations to the right shard. Driver connections target mongos, not the shards directly. You run two or three mongos behind a TCP load balancer or per-app-host.

Three things have to be true at the wire level for the cluster to function: every node trusts every other node via a shared keyFile (and TLS in production), every node can resolve every other node by the exact hostname declared in rs.initiate(), and the config RS is up before any shard is added. Reverse that order and the cluster will technically come up but the metadata will be inconsistent.

How to verify

After the installer below has been run on all 9 mongod hosts and the 2 mongos routers, status from a mongos should look like this:

mongosh --tls --tlsCAFile /etc/mongo/tls/ca.pem \
  --tlsCertificateKeyFile /etc/mongo/tls/router.pem \
  --host mongos01.internal --eval "sh.status()" \
  | head -40
# --- Sharding Status ---
#   sharding version: { "clusterId": ..., "lastMod": 2 }
#   shards:
#     {  "_id" : "shard01",  "host" : "shard01/shard01a:27018,shard01b:27018,shard01c:27018",  "state" : 1 }
#     {  "_id" : "shard02",  "host" : "shard02/shard02a:27018,shard02b:27018,shard02c:27018",  "state" : 1 }
#   balancer:
#     Currently enabled: yes
#     Currently running: no

Chunk distribution for a sharded collection — should converge over time, not concentrate on one shard:

db.getSiblingDB("appdb").collection.getShardDistribution()
// Shard shard01 at shard01/shard01a:27018,shard01b:27018,shard01c:27018
//  data : 4.32 GiB docs : 5183921 chunks : 12
// Shard shard02 at shard02/shard02a:27018,shard02b:27018,shard02c:27018
//  data : 4.18 GiB docs : 4982113 chunks : 11

Balancer activity (should be idle most of the time, active during rebalances):

sh.isBalancerRunning()
sh.getBalancerState()
db.getSiblingDB("config").changelog.find({}).sort({time:-1}).limit(5)

CSRS health — this is the canary for the whole cluster:

mongosh --tls --tlsCAFile /etc/mongo/tls/ca.pem \
  --tlsCertificateKeyFile /etc/mongo/tls/router.pem \
  --host cfg01.internal --eval "rs.status()" \
  | jq '.members[] | {name, stateStr, health}'

If any CSRS member shows health 0 or a stateStr other than PRIMARY/SECONDARY for more than a few seconds, page someone. The cluster won’t accept new chunk splits or balancer moves while CSRS is degraded.

The fix

Save the script as /root/setup-mongo-sharded.sh and run it on each of the 9 mongod hosts and 2 mongos hosts after editing the ROLE, NODE_NAME, NODE_IP, and PEER_* variables at the top. The installer is the same script across all roles — the ROLE variable decides which config blocks get written. The roles are: config, shard01, shard02, mongos. After all 11 hosts are installed, run the coordinator block from cfg01 to initiate the three replica sets, then add the shards from mongos01.

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

### AlmaLinux 9 MongoDB 7 sharded cluster installer
### Role-aware: ROLE=config | shard01 | shard02 | mongos
### 11 hosts total: 3 config + 3 shard01 + 3 shard02 + 2 mongos

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

# === EDIT PER HOST ===
ROLE="config"             # config | shard01 | shard02 | mongos
NODE_NAME="cfg01"         # cfg01..03 | shard01a..c | shard02a..c | mongos01..02
NODE_IP="10.30.0.11"
# Per-role peer arrays
CFG_NAMES=("cfg01" "cfg02" "cfg03")
CFG_IPS=("10.30.0.11" "10.30.0.12" "10.30.0.13")
SHARD01_NAMES=("shard01a" "shard01b" "shard01c")
SHARD01_IPS=("10.30.1.11" "10.30.1.12" "10.30.1.13")
SHARD02_NAMES=("shard02a" "shard02b" "shard02c")
SHARD02_IPS=("10.30.2.11" "10.30.2.12" "10.30.2.13")
MONGOS_NAMES=("mongos01" "mongos02")
MONGOS_IPS=("10.30.9.11" "10.30.9.12")
ROOT_PASSWORD="CHANGE_ME_ROOT"
# =====================

echo
echo "========================================"
echo "MongoDB ${ROLE} node ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo

case "${ROLE}" in
  config)  MONGO_PORT=27019 ;;
  shard01|shard02) MONGO_PORT=27018 ;;
  mongos)  MONGO_PORT=27017 ;;
  *) echo "Unknown ROLE=${ROLE}"; exit 1 ;;
esac

echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y install \
  curl wget chrony fail2ban dnf-automatic \
  policycoreutils-python-utils lsof tcpdump bind-utils tar gzip \
  iproute net-tools jq socat openssl xfsprogs rsync

systemctl enable --now chronyd

echo "==> Hostname + hosts file (full mesh resolution)"
hostnamectl set-hostname "${NODE_NAME}.internal"
{
  echo "127.0.0.1 localhost"
  for i in "${!CFG_NAMES[@]}";    do echo "${CFG_IPS[$i]} ${CFG_NAMES[$i]}.internal ${CFG_NAMES[$i]}"; done
  for i in "${!SHARD01_NAMES[@]}"; do echo "${SHARD01_IPS[$i]} ${SHARD01_NAMES[$i]}.internal ${SHARD01_NAMES[$i]}"; done
  for i in "${!SHARD02_NAMES[@]}"; do echo "${SHARD02_IPS[$i]} ${SHARD02_NAMES[$i]}.internal ${SHARD02_NAMES[$i]}"; done
  for i in "${!MONGOS_NAMES[@]}"; do echo "${MONGOS_IPS[$i]} ${MONGOS_NAMES[$i]}.internal ${MONGOS_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 sshd

echo "==> fail2ban + automatic security updates"
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

cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
DNFAUTO
systemctl enable --now dnf-automatic.timer

echo "==> SELinux enforcing"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
setenforce 1 || true

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'
mongod soft nofile 64000
mongod hard nofile 64000
mongod soft nproc 64000
mongod hard nproc 64000
LIMITS

echo "==> Disable transparent hugepages"
cat > /etc/systemd/system/disable-thp.service <<'THP'
[Unit]
Description=Disable Transparent Huge Pages
DefaultDependencies=false
After=sysinit.target local-fs.target
Before=mongod.service mongos.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 "==> MongoDB 7.0 yum repository"
cat > /etc/yum.repos.d/mongodb-org-7.0.repo <<'REPO'
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc
REPO

dnf -y install mongodb-org mongodb-mongosh

echo "==> Persistent data volume (mongod only)"
if [[ "${ROLE}" != "mongos" ]]; then
  DATA_DEVICE="/dev/sdb"
  DATA_MOUNT="/var/lib/mongo"
  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}")
    grep -q "${UUID}" /etc/fstab || \
      echo "UUID=${UUID} ${DATA_MOUNT} xfs defaults,noatime,nodiratime 0 0" >> /etc/fstab
    mount -a
  fi
  chown -R mongod:mongod "${DATA_MOUNT}"
fi

echo "==> TLS material directory"
TLS_DIR="/etc/mongo/tls"
mkdir -p "${TLS_DIR}"
chown -R mongod:mongod /etc/mongo 2>/dev/null || true
chmod 700 "${TLS_DIR}"

# Generate the cluster CA on cfg01 — distribute via rsync to all 11 hosts
if [[ "${NODE_NAME}" == "cfg01" ]] && [[ ! -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-cluster-ca" -out "${TLS_DIR}/ca.pem"
  openssl rand -base64 756 > "${TLS_DIR}/mongo.keyfile"
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

if [[ -f "${TLS_DIR}/mongo.keyfile" ]]; then
  chmod 400 "${TLS_DIR}/mongo.keyfile"
  chown mongod:mongod "${TLS_DIR}/mongo.keyfile" 2>/dev/null || true
fi

chown -R mongod:mongod /etc/mongo 2>/dev/null || true
mkdir -p /var/log/mongo
chown -R mongod:mongod /var/log/mongo 2>/dev/null || true

# Open intra-cluster ports
echo "==> firewalld rules"
dnf -y install firewalld
systemctl enable --now firewalld
ALL_IPS=(${CFG_IPS[@]} ${SHARD01_IPS[@]} ${SHARD02_IPS[@]} ${MONGOS_IPS[@]})
for ip in "${ALL_IPS[@]}"; do
  firewall-cmd --add-rich-rule="rule family=ipv4 source address=${ip}/32 port port=${MONGO_PORT} protocol=tcp accept" --permanent
done
firewall-cmd --reload

echo "==> Writing config for ROLE=${ROLE}"

case "${ROLE}" in
  config)
    cat > /etc/mongod.conf <<EOF
storage:
  dbPath: /var/lib/mongo
  wiredTiger:
    engineConfig:
      cacheSizeGB: 2

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

net:
  bindIp: 127.0.0.1,${NODE_IP}
  port: 27019
  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: cfgrs

sharding:
  clusterRole: configsvr

operationProfiling:
  slowOpThresholdMs: 200
  mode: slowOp
EOF
    SERVICE="mongod"
    ;;

  shard01|shard02)
    cat > /etc/mongod.conf <<EOF
storage:
  dbPath: /var/lib/mongo
  wiredTiger:
    engineConfig:
      cacheSizeGB: 6
      journalCompressor: snappy
    collectionConfig:
      blockCompressor: snappy

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

net:
  bindIp: 127.0.0.1,${NODE_IP}
  port: 27018
  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: ${ROLE}
  oplogSizeMB: 51200

sharding:
  clusterRole: shardsvr

operationProfiling:
  slowOpThresholdMs: 200
  mode: slowOp
EOF
    SERVICE="mongod"
    ;;

  mongos)
    cat > /etc/mongos.conf <<EOF
systemLog:
  destination: file
  path: /var/log/mongo/mongos.log
  logAppend: true
  logRotate: reopen

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:
  keyFile: ${TLS_DIR}/mongo.keyfile

sharding:
  configDB: cfgrs/${CFG_NAMES[0]}.internal:27019,${CFG_NAMES[1]}.internal:27019,${CFG_NAMES[2]}.internal:27019
EOF

    # Create a mongos systemd unit (none ships by default)
    cat > /etc/systemd/system/mongos.service <<'UNIT'
[Unit]
Description=MongoDB Sharded Cluster Router (mongos)
After=network.target

[Service]
Type=simple
User=mongod
Group=mongod
ExecStart=/usr/bin/mongos --config /etc/mongos.conf
Restart=on-failure
LimitNOFILE=64000
LimitNPROC=64000

[Install]
WantedBy=multi-user.target
UNIT
    systemctl daemon-reload
    SERVICE="mongos"
    ;;
esac

# Ulimit drop-in
mkdir -p /etc/systemd/system/${SERVICE}.service.d
cat > /etc/systemd/system/${SERVICE}.service.d/ulimits.conf <<'UNIT'
[Service]
LimitFSIZE=infinity
LimitCPU=infinity
LimitAS=infinity
LimitNOFILE=64000
LimitNPROC=64000
LimitMEMLOCK=infinity
UNIT
systemctl daemon-reload

if [[ -f "${TLS_DIR}/mongo.keyfile" ]] && [[ -f "${TLS_DIR}/${NODE_NAME}.pem" ]]; then
  echo "==> Enabling and starting ${SERVICE}"
  systemctl enable --now ${SERVICE}
else
  echo "==> ${SERVICE} NOT started — CA + keyFile not yet present on ${NODE_NAME}"
  echo "    Re-run this script after rsync from cfg01 has placed them."
  exit 0
fi

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

echo
echo "========================================"
echo "DONE on ${NODE_NAME} (${ROLE})"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ":(27017|27018|27019)\b" || true
echo
echo "Coordinator steps follow this installer — see runbook tail."

After every host has been provisioned (run the installer 11 times with the right ROLE / NODE_NAME / NODE_IP), distribute the CA and keyFile from cfg01:

# From cfg01 — after the installer there generated ca.* and mongo.keyfile
ALL_HOSTS=(cfg02 cfg03 \
           shard01a shard01b shard01c \
           shard02a shard02b shard02c \
           mongos01 mongos02)
for h in "${ALL_HOSTS[@]}"; do
  rsync -a /etc/mongo/tls/ca.{pem,key} /etc/mongo/tls/mongo.keyfile \
    root@${h}.internal:/etc/mongo/tls/
done

Re-run the installer on each host that came up without TLS material in place. Then initiate the three replica sets in order — config first:

# Initiate CSRS — from cfg01
mongosh --tls --tlsCAFile /etc/mongo/tls/ca.pem \
  --tlsCertificateKeyFile /etc/mongo/tls/cfg01.pem \
  --host cfg01.internal --port 27019 <<'JS'
rs.initiate({
  _id: "cfgrs",
  configsvr: true,
  members: [
    { _id: 0, host: "cfg01.internal:27019" },
    { _id: 1, host: "cfg02.internal:27019" },
    { _id: 2, host: "cfg03.internal:27019" }
  ]
});
sleep(5000);
db.getSiblingDB("admin").createUser({
  user: "root", pwd: "CHANGE_ME_ROOT",
  roles: [{ role: "root", db: "admin" }]
});
JS

# Initiate shard01 — from shard01a
mongosh --tls --tlsCAFile /etc/mongo/tls/ca.pem \
  --tlsCertificateKeyFile /etc/mongo/tls/shard01a.pem \
  --host shard01a.internal --port 27018 <<'JS'
rs.initiate({
  _id: "shard01",
  members: [
    { _id: 0, host: "shard01a.internal:27018" },
    { _id: 1, host: "shard01b.internal:27018" },
    { _id: 2, host: "shard01c.internal:27018" }
  ]
});
JS

# Initiate shard02 — from shard02a
mongosh --tls --tlsCAFile /etc/mongo/tls/ca.pem \
  --tlsCertificateKeyFile /etc/mongo/tls/shard02a.pem \
  --host shard02a.internal --port 27018 <<'JS'
rs.initiate({
  _id: "shard02",
  members: [
    { _id: 0, host: "shard02a.internal:27018" },
    { _id: 1, host: "shard02b.internal:27018" },
    { _id: 2, host: "shard02c.internal:27018" }
  ]
});
JS

# Add shards from mongos01
mongosh --tls --tlsCAFile /etc/mongo/tls/ca.pem \
  --tlsCertificateKeyFile /etc/mongo/tls/mongos01.pem \
  --host mongos01.internal -u root -p 'CHANGE_ME_ROOT' --authenticationDatabase admin <<'JS'
sh.addShard("shard01/shard01a.internal:27018,shard01b.internal:27018,shard01c.internal:27018");
sh.addShard("shard02/shard02a.internal:27018,shard02b.internal:27018,shard02c.internal:27018");
sh.status();
JS

Once sh.status() shows both shards state: 1, enable sharding on a database and shard a collection on a thoughtful key (high cardinality, monotonic-free if at all possible — hashed shard keys avoid hot chunks on insert):

sh.enableSharding("appdb");
db.getSiblingDB("appdb").events.createIndex({ tenant_id: "hashed" });
sh.shardCollection("appdb.events", { tenant_id: "hashed" });

Then start trickling production write traffic in. Watch the balancer log (db.getSiblingDB("config").changelog) for chunk migrations during the first hour — long-running migrations on a high-write key indicate the key is wrong and you need to revisit it before the dataset gets unwieldy.

Treat the CSRS as the most fragile part of the topology. Page on any of: CSRS member health < 1 for more than 60s, any shard election lag > 30s, balancer disabled when you didn’t disable it, mongos connection failures to CSRS. Snapshot the data volumes on all three tiers; snapshots in the shard tier alone aren’t sufficient — without coherent CSRS metadata, a recovered shard is just a pile of bytes.

To run a sharded MongoDB tier without owning the runbook, our Cloud Compute team operates the whole topology under Managed Cloud Ops with shard-balance and CSRS-health alerts on our monitoring plane — or book a scoping call to plan the migration.