Skip to content

Deploying Rocket.Chat self-host on AlmaLinux 9 with a MongoDB replica set

Stand up a hardened self-hosted Rocket.Chat on AlmaLinux 9 — MongoDB 7 three-node replica set as the persistence layer, nginx + Let's Encrypt reverse proxy, mobile push gateway.

You self-host Rocket.Chat for the internal company chat — leadership wants a chat product they control, the security review needs end-to-end encrypted DMs the SaaS plan does not offer at the operator’s tier, and integrations with internal tooling are easier when the database is a connection string away. The Docker quickstart works, MongoDB comes up as a single node, the integration team writes ten outbound webhook configs, and two months later the Meteor app starts logging MongoError: not master and slaveOk=false every few hours, full-text search returns nothing across the last week of messages because the index build queue is stuck behind an oplog tail that never advances, and a routine MongoDB restart drops 90 seconds of messages on the floor because there is no replica to fail over to. A self-hosted Rocket.Chat that holds up under real traffic is the same product wired up to a real database — not the same product wired up to a database that happens to be running.

What’s happening

Rocket.Chat is a Meteor app. Meteor’s real-time data layer (livedata) does not poll MongoDB — it tails the oplog and replays operations to subscribed clients. The oplog is only available on a MongoDB replica set, never on a standalone mongod, and the official documentation has said since 2018 that production Rocket.Chat needs the oplog enabled. A single-node deployment running standalone mongod technically boots, but Meteor falls back to a much slower poll-and-diff loop that scales badly with concurrent users and silently breaks features that rely on cross-app reactivity — most visibly the unread badge count and the typing indicator.

The minimum-viable production layout is three MongoDB nodes in a replica set on a private network, Rocket.Chat connecting to all three with a replicaSet=rs0 connection string and a separate MONGO_OPLOG_URL pointing at the local database, nginx out front terminating TLS, and the official push gateway registered for mobile delivery (same model as Zulip — a community-run bouncer that relays APNS/FCM payloads on the operator’s behalf). MongoDB itself needs authorization: enabled, a keyfile-authenticated replica set, and the wiredTiger.engineConfig.cacheSizeGB parameter set to roughly 50% of host RAM minus what Rocket.Chat consumes — left at default, the engine tries to grab everything and the OOM killer eventually takes Rocket.Chat instead of mongod.

Rocket.Chat on this version of AlmaLinux ships as a tarball you install with systemd rather than a container — it’s faster, it’s easier to debug when things go sideways at 2am, and it avoids the Docker-on-AlmaLinux SELinux interactions that surprise people who haven’t run them before. The Node.js runtime is the version pinned by the Rocket.Chat release notes — running a newer LTS will hit hard breakage in obscure Meteor internals.

How to verify

Replica set health from any node:

mongosh --tls --tlsCertificateKeyFile /etc/mongo/keyfile.pem \
  -u rsadmin --authenticationDatabase admin --eval 'rs.status().members.forEach(m=>print(m.name,m.stateStr,m.health))'
# rocket01:27017 PRIMARY 1
# rocket02:27017 SECONDARY 1
# rocket03:27017 SECONDARY 1

If any member is (not reachable/healthy) for more than a couple of seconds, the others have to elect a new primary — Rocket.Chat will retry but writes block for the election window (~10s with default settings).

Confirm Rocket.Chat is tailing the oplog rather than falling back to poll-and-diff:

journalctl -u rocketchat --since "10 min ago" \
  | grep -E '(oplog|Tailing|MongoConnector)'
# Tailing oplog: local.oplog.rs

If you see Falling back to polling — oplog access denied or MONGO_OPLOG_URL not set, the connection string is wrong. Real-time features will degrade quietly.

The host should expose only :80, :443, and :22:

ss -lntp | grep -E ':(80|443|3000|27017)\b'
# 0.0.0.0:443    nginx
# 0.0.0.0:80     nginx
# 127.0.0.1:3000 rocketchat
# 10.10.0.x:27017 mongod (private interface only)

27017 must never be on 0.0.0.0. Bind it to the private interface or to 127.0.0.1 if all three Mongo nodes are co-tenant on the Rocket.Chat host (acceptable for very small deployments but fragile — one host failure takes the entire cluster).

Confirm the push gateway is registered:

curl -fsS -H "X-Auth-Token: $ADMIN_TOKEN" -H "X-User-Id: $ADMIN_USER_ID" \
  https://chat.example.com/api/v1/push.token \
  | jq .gateway_registered
# true

If false, mobile clients will receive in-app delivery only — no banner alerts when the app is backgrounded.

The fix

Save the script below as /root/setup-rocketchat-almalinux9.sh on every node. It runs in two modes — pass MODE=mongo to install only MongoDB on a database node, pass MODE=rocketchat to install only the Rocket.Chat application on the app node. For a small deployment you can run both modes on each of three nodes; for anything larger, put the Rocket.Chat app on its own host with a separate three-node MongoDB cluster on the private network. The script does base hardening (SELinux enforcing, fail2ban, dnf-automatic, SSH key-only), MongoDB 7 from the official repo with WiredTiger cache sized for the host, a keyfile-authenticated replica set named rs0, the official Rocket.Chat tarball install with the pinned Node.js version, a systemd unit with LimitNOFILE=64000, nginx terminating TLS with the WebSocket upgrade headers Rocket.Chat needs, Let’s Encrypt via certbot, and a poll loop that fails loudly if Rocket.Chat or the replica set doesn’t come up.

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

### AlmaLinux 9 Rocket.Chat self-host installer
### MODE=mongo            — install only MongoDB
### MODE=rocketchat       — install only the Rocket.Chat app
### MODE=both             — install both on this host (small-deployment shortcut)
### Run on each MongoDB node first; the replica set must be initiated from rocket01.

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

: "${ROCKETCHAT_DOMAIN:?Set ROCKETCHAT_DOMAIN=chat.example.com}"
: "${ROCKETCHAT_EMAIL:?Set ROCKETCHAT_EMAIL=ops@example.com for Let's Encrypt}"
MODE="${MODE:-both}"
NODE_NAME="${NODE_NAME:-rocket01}"
NODE_IP="${NODE_IP:-10.10.0.11}"
PEER_IPS=("${PEER_IPS[@]:-10.10.0.11 10.10.0.12 10.10.0.13}")
PEER_NAMES=("${PEER_NAMES[@]:-rocket01 rocket02 rocket03}")
MONGO_RS_NAME="${MONGO_RS_NAME:-rs0}"
MONGO_ADMIN_USER="${MONGO_ADMIN_USER:-rsadmin}"
MONGO_ADMIN_PASSWORD="${MONGO_ADMIN_PASSWORD:-$(openssl rand -hex 24)}"
MONGO_APP_USER="${MONGO_APP_USER:-rocketchat}"
MONGO_APP_PASSWORD="${MONGO_APP_PASSWORD:-$(openssl rand -hex 24)}"
MONGO_CACHE_GB="${MONGO_CACHE_GB:-4}"   # tune to ~50% RAM minus app footprint
ROCKETCHAT_VERSION="${ROCKETCHAT_VERSION:-7.2.1}"
NODE_VERSION="${NODE_VERSION:-14.21.4}"

echo
echo "========================================"
echo "Rocket.Chat AlmaLinux 9 — ${NODE_NAME} (${MODE})"
echo "========================================"
echo

echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y install vim curl wget ca-certificates gnupg2 \
  chrony fail2ban dnf-automatic \
  policycoreutils-python-utils lsof tcpdump bind-utils tar gzip \
  iproute net-tools jq xz openssl firewalld

systemctl enable --now chronyd

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

echo "==> Kernel/sysctl tuning"
cat > /etc/sysctl.d/99-rocketchat.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.tcp_keepalive_time = 600
fs.file-max = 2097152
vm.swappiness = 1
vm.max_map_count = 262144
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-rocketchat.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
mongod soft nofile 200000
mongod hard nofile 200000
rocketchat soft nofile 64000
rocketchat hard nofile 64000
LIMITS

echo "==> Hardening SSH"
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"
mkdir -p /etc/fail2ban/jail.d
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 "==> Configuring firewalld"
systemctl enable --now firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
# MongoDB only between replica set members
for peer in "${PEER_IPS[@]}"; do
  firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='${peer}' port port='27017' protocol='tcp' accept"
done
firewall-cmd --reload

if [[ "${MODE}" == "mongo" || "${MODE}" == "both" ]]; then
  echo "==> Installing MongoDB 7"
  cat > /etc/yum.repos.d/mongodb-org-7.0.repo <<'MONGOREPO'
[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://pgp.mongodb.com/server-7.0.asc
MONGOREPO
  dnf -y install mongodb-org

  echo "==> Generating MongoDB keyfile for replica set authentication"
  mkdir -p /etc/mongo
  if [[ ! -f /etc/mongo/keyfile.pem ]]; then
    openssl rand -base64 756 > /etc/mongo/keyfile.pem
  fi
  chmod 600 /etc/mongo/keyfile.pem
  chown -R mongod:mongod /etc/mongo

  echo "==> Writing /etc/mongod.conf"
  cat > /etc/mongod.conf <<MCONF
storage:
  dbPath: /var/lib/mongo
  wiredTiger:
    engineConfig:
      cacheSizeGB: ${MONGO_CACHE_GB}

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

processManagement:
  fork: false
  pidFilePath: /var/run/mongodb/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27017
  bindIp: 127.0.0.1,${NODE_IP}

security:
  authorization: enabled
  keyFile: /etc/mongo/keyfile.pem

replication:
  replSetName: ${MONGO_RS_NAME}

operationProfiling:
  slowOpThresholdMs: 200
MCONF

  systemctl enable --now mongod
  sleep 8

  # Replica set initiation runs only on rocket01 — and only after every node is reachable.
  if [[ "${NODE_NAME}" == "${PEER_NAMES[0]}" ]]; then
    echo "==> Waiting for all MongoDB peers to be reachable"
    for peer in "${PEER_IPS[@]}"; do
      for i in {1..60}; do
        if nc -z -w 1 "${peer}" 27017 2>/dev/null; then break; fi
        sleep 2
      done
    done

    echo "==> Initiating replica set ${MONGO_RS_NAME} from ${NODE_NAME}"
    mongosh --quiet --eval "
      try {
        rs.status();
        print('Replica set already initiated');
      } catch (e) {
        rs.initiate({
          _id: '${MONGO_RS_NAME}',
          members: [
            { _id: 0, host: '${PEER_IPS[0]}:27017', priority: 2 },
            { _id: 1, host: '${PEER_IPS[1]}:27017', priority: 1 },
            { _id: 2, host: '${PEER_IPS[2]}:27017', priority: 1 }
          ]
        });
      }
    "

    sleep 15

    echo "==> Creating admin and application users"
    mongosh --quiet --eval "
      use admin;
      try {
        db.createUser({
          user: '${MONGO_ADMIN_USER}',
          pwd: '${MONGO_ADMIN_PASSWORD}',
          roles: [ { role: 'root', db: 'admin' } ]
        });
      } catch(e) { print('admin user exists'); }
    "
    sleep 3
    mongosh --quiet -u "${MONGO_ADMIN_USER}" -p "${MONGO_ADMIN_PASSWORD}" \
      --authenticationDatabase admin --eval "
      use rocketchat;
      try {
        db.createUser({
          user: '${MONGO_APP_USER}',
          pwd: '${MONGO_APP_PASSWORD}',
          roles: [
            { role: 'readWrite', db: 'rocketchat' },
            { role: 'read', db: 'local' }
          ]
        });
      } catch(e) { print('app user exists'); }
    "
  fi
fi

if [[ "${MODE}" == "rocketchat" || "${MODE}" == "both" ]]; then
  echo "==> Installing Node.js ${NODE_VERSION} via NodeSource binary tarball"
  useradd -r -m -d /opt/rocketchat -s /usr/sbin/nologin rocketchat || true
  cd /opt
  curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" \
    -o /opt/node-${NODE_VERSION}.tar.xz
  tar -xJf /opt/node-${NODE_VERSION}.tar.xz -C /opt
  ln -sfn /opt/node-v${NODE_VERSION}-linux-x64 /opt/node
  echo 'PATH=/opt/node/bin:$PATH' > /etc/profile.d/rocketchat-node.sh
  /opt/node/bin/node --version

  echo "==> Fetching Rocket.Chat ${ROCKETCHAT_VERSION}"
  cd /opt
  curl -fsSL "https://releases.rocket.chat/${ROCKETCHAT_VERSION}/download" -o rocketchat.tgz
  tar -xzf rocketchat.tgz
  mv bundle "rocketchat-${ROCKETCHAT_VERSION}"
  rm -f rocketchat.tgz
  ln -sfn "/opt/rocketchat-${ROCKETCHAT_VERSION}" /opt/rocketchat-current

  cd /opt/rocketchat-current/programs/server
  sudo -u rocketchat /opt/node/bin/npm install --omit=dev --no-audit --no-fund

  chown -R rocketchat:rocketchat "/opt/rocketchat-${ROCKETCHAT_VERSION}"

  # Build the Mongo connection string from peer IPs
  MONGO_HOSTS=$(IFS=,; echo "${PEER_IPS[*]}")
  MONGO_HOSTS_WITH_PORTS=$(echo "${MONGO_HOSTS}" | sed 's/,/:27017,/g')
  MONGO_HOSTS_WITH_PORTS="${MONGO_HOSTS_WITH_PORTS}:27017"

  cat > /opt/rocketchat/rocketchat.env <<ENVFILE
ROOT_URL=https://${ROCKETCHAT_DOMAIN}
PORT=3000
MONGO_URL=mongodb://${MONGO_APP_USER}:${MONGO_APP_PASSWORD}@${MONGO_HOSTS_WITH_PORTS}/rocketchat?replicaSet=${MONGO_RS_NAME}&authSource=rocketchat
MONGO_OPLOG_URL=mongodb://${MONGO_APP_USER}:${MONGO_APP_PASSWORD}@${MONGO_HOSTS_WITH_PORTS}/local?replicaSet=${MONGO_RS_NAME}&authSource=rocketchat
DEPLOY_METHOD=tar
DEPLOY_PLATFORM=stackharbor
NODE_OPTIONS=--max-old-space-size=2048
ENVFILE
  chmod 600 /opt/rocketchat/rocketchat.env
  chown rocketchat:rocketchat /opt/rocketchat/rocketchat.env

  cat > /etc/systemd/system/rocketchat.service <<'UNIT'
[Unit]
Description=Rocket.Chat
After=network.target

[Service]
Type=simple
User=rocketchat
Group=rocketchat
EnvironmentFile=/opt/rocketchat/rocketchat.env
ExecStart=/opt/node/bin/node /opt/rocketchat-current/main.js
Restart=on-failure
RestartSec=10
LimitNOFILE=64000
StandardOutput=journal
StandardError=journal
SyslogIdentifier=rocketchat

[Install]
WantedBy=multi-user.target
UNIT

  systemctl daemon-reload
  systemctl enable --now rocketchat
fi

echo "==> Installing nginx + certbot (app node only)"
if [[ "${MODE}" == "rocketchat" || "${MODE}" == "both" ]]; then
  dnf -y install nginx certbot python3-certbot-nginx

  cat > /etc/nginx/conf.d/rocketchat.conf <<NGINX
upstream rocketchat_backend {
    server 127.0.0.1:3000;
    keepalive 32;
}

server {
    listen 80;
    listen [::]:80;
    server_name ${ROCKETCHAT_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${ROCKETCHAT_DOMAIN};

    client_max_body_size 200M;
    proxy_read_timeout   600s;
    proxy_send_timeout   600s;
    proxy_connect_timeout 60s;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    location / {
        proxy_pass http://rocketchat_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_set_header X-Nginx-Proxy true;
        proxy_redirect off;
    }
}
NGINX

  nginx -t
  systemctl enable --now nginx
  systemctl reload nginx

  certbot --nginx --non-interactive --agree-tos \
    -m "${ROCKETCHAT_EMAIL}" -d "${ROCKETCHAT_DOMAIN}" --redirect

  systemctl enable --now certbot-renew.timer || systemctl enable --now certbot.timer
fi

echo "==> Waiting for Rocket.Chat on 127.0.0.1:3000"
if [[ "${MODE}" == "rocketchat" || "${MODE}" == "both" ]]; then
  for i in {1..180}; do
    if ss -lntp | grep -q '127.0.0.1:3000'; then
      break
    fi
    sleep 2
  done

  if ! ss -lntp | grep -q '127.0.0.1:3000'; then
    echo "Rocket.Chat failed to listen on 127.0.0.1:3000"
    journalctl -u rocketchat --no-pager --since '5 min ago' | tail -100 || true
    exit 1
  fi
fi

echo
echo "========================================"
echo "DONE — ${NODE_NAME}"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|3000|27017)\b' || true

echo
echo "Services:"
systemctl is-active mongod rocketchat nginx fail2ban chronyd 2>/dev/null || true

if [[ "${NODE_NAME}" == "${PEER_NAMES[0]}" && ( "${MODE}" == "mongo" || "${MODE}" == "both" ) ]]; then
  echo
  echo "Replica set status:"
  mongosh --quiet -u "${MONGO_ADMIN_USER}" -p "${MONGO_ADMIN_PASSWORD}" --authenticationDatabase admin \
    --eval 'rs.status().members.forEach(m=>print(m.name,m.stateStr,m.health))' || true
fi

echo
echo "Web UI:"
echo "https://${ROCKETCHAT_DOMAIN}/"

echo
echo "Secrets:"
echo "  MongoDB admin: ${MONGO_ADMIN_USER} / (written to /opt/rocketchat/rocketchat.env on the app node)"
echo "  MongoDB app:   ${MONGO_APP_USER}   / (same)"
echo "  Move /opt/rocketchat/rocketchat.env into your secrets manager and chmod 600 the file."

echo
echo "Next steps:"
echo "1. Open the URL — the first user that signs up becomes the workspace owner."
echo "2. Admin > Workspace > Mobile > register with cloud push gateway."
echo "3. Admin > Permissions — turn off 'create direct messages' for guests if you accept them."
echo "4. VM-level backup must cover /var/lib/mongo on every MongoDB node. mongodump alone is not enough."

Make it executable and run it. For three co-tenant nodes:

chmod 700 /root/setup-rocketchat-almalinux9.sh

# rocket01 (primary candidate)
NODE_NAME=rocket01 NODE_IP=10.10.0.11 \
ROCKETCHAT_DOMAIN=chat.example.com ROCKETCHAT_EMAIL=ops@example.com \
PEER_IPS=(10.10.0.11 10.10.0.12 10.10.0.13) \
PEER_NAMES=(rocket01 rocket02 rocket03) \
MODE=both \
/root/setup-rocketchat-almalinux9.sh

# rocket02 and rocket03 — same env, set NODE_NAME and NODE_IP appropriately, MODE=mongo

After install on all three nodes, the replica set is initiated by the script on rocket01. Open https://chat.example.com/ and the first user that signs up becomes the workspace owner — pick that account up immediately, then under Admin → Workspace → Mobile register with the Rocket.Chat cloud push gateway so that backgrounded mobile clients receive banner alerts. The MONGO_OPLOG_URL in /opt/rocketchat/rocketchat.env is what makes Meteor tail the oplog rather than poll — if you ever see “Falling back to polling” in the rocketchat journal, that line is wrong. Confirm VM-level snapshots cover /var/lib/mongo on every database node; mongodump is a useful additional layer (point-in-time restore of a corrupted collection) but it is not a replacement for snapshots of the data directory.

Run this Rocket.Chat on Stack Harbor’s managed dedicated cloud with patching, monitoring, and Sev-1 escalation included — or book a discovery call if you need the MongoDB replica set sized and the cutover from a SaaS chat planned.