Vous auto-hébergez Rocket.Chat pour la messagerie interne de l’entreprise — la direction veut un produit de chat sous son contrôle, la revue de sécurité a besoin de DM chiffrés bout-en-bout que le plan SaaS n’offre pas au palier de l’opérateur, et les intégrations avec l’outillage interne sont plus simples quand la base de données est à une chaîne de connexion. Le quickstart Docker fonctionne, MongoDB monte en nœud unique, l’équipe d’intégration écrit dix configs de webhooks sortants, et deux mois plus tard l’app Meteor log MongoError: not master and slaveOk=false toutes les quelques heures, la recherche plein texte ne retourne rien pour la dernière semaine de messages parce que la file de construction d’index est bloquée derrière une queue d’oplog qui n’avance jamais, et un redémarrage de routine de MongoDB perd 90 secondes de messages parce qu’il n’y a pas de réplica vers lequel basculer. Un Rocket.Chat auto-hébergé qui tient sous le trafic réel, c’est le même produit câblé à une vraie base de données — pas le même produit câblé à une base de données qui se trouve tourner.
Ce qui se passe
Rocket.Chat est une app Meteor. La couche de données temps réel de Meteor (livedata) ne fait pas de polling MongoDB — elle suit l’oplog et rejoue les opérations vers les clients abonnés. L’oplog n’est disponible que sur un replica set MongoDB, jamais sur un mongod standalone, et la documentation officielle dit depuis 2018 que Rocket.Chat en production exige l’oplog activé. Un déploiement nœud unique en standalone démarre techniquement, mais Meteor retombe sur une boucle poll-and-diff bien plus lente qui scale mal avec les utilisateurs concurrents et casse silencieusement les fonctionnalités qui dépendent de la réactivité cross-app — le plus visiblement le compteur de non-lus et l’indicateur de saisie.
L’organisation minimale viable en production, c’est trois nœuds MongoDB en replica set sur un réseau privé, Rocket.Chat se connectant aux trois avec une chaîne replicaSet=rs0 et un MONGO_OPLOG_URL séparé pointant la base local, nginx en front qui termine TLS, et la passerelle push officielle enrôlée pour la livraison mobile (même modèle que Zulip — un bouncer communautaire qui relaie les payloads APNS/FCM pour le compte de l’opérateur). MongoDB lui-même a besoin de authorization: enabled, d’un replica set authentifié par keyfile, et du paramètre wiredTiger.engineConfig.cacheSizeGB réglé à environ 50 % de la RAM hôte moins ce que Rocket.Chat consomme — laissé à la valeur par défaut, le moteur essaie de tout prendre et l’OOM killer finit par sacrifier Rocket.Chat à la place de mongod.
Rocket.Chat sur cette version d’AlmaLinux est livré sous forme de tarball à installer avec systemd plutôt qu’en conteneur — c’est plus rapide, plus simple à déboguer quand ça part en vrille à 2h du matin, et ça évite les interactions Docker-sur-AlmaLinux SELinux qui surprennent ceux qui ne les ont pas rencontrées. Le runtime Node.js est la version épinglée par les release notes Rocket.Chat — utiliser un LTS plus récent provoque des cassures profondes dans des internals Meteor obscurs.
Comment vérifier
Santé du replica set depuis n’importe quel nœud :
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
Si un membre passe en (not reachable/healthy) plus que quelques secondes, les autres doivent élire un nouveau primaire — Rocket.Chat retentera mais les écritures se bloquent pendant la fenêtre d’élection (~10 s avec les réglages par défaut).
Vérifier que Rocket.Chat suit bien l’oplog et n’est pas retombé en poll-and-diff :
journalctl -u rocketchat --since "10 min ago" \
| grep -E '(oplog|Tailing|MongoConnector)'
# Tailing oplog: local.oplog.rs
Si vous voyez Falling back to polling — oplog access denied ou MONGO_OPLOG_URL not set, la chaîne de connexion est mauvaise. Les fonctionnalités temps réel se dégraderont en silence.
L’hôte ne doit exposer que :80, :443 et :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 (interface privée uniquement)
27017 ne doit jamais être sur 0.0.0.0. Liez-le à l’interface privée ou à 127.0.0.1 si les trois nœuds Mongo sont co-locataires de l’hôte Rocket.Chat (acceptable pour des très petits déploiements mais fragile — une panne d’hôte emporte toute la grappe).
Vérifier que la passerelle push est enrôlée :
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
Si false, les clients mobile ne reçoivent que la livraison in-app — aucune alerte bannière quand l’app est en arrière-plan.
Le correctif
Enregistrez le script ci-dessous sous /root/setup-rocketchat-almalinux9.sh sur chaque nœud. Il tourne dans deux modes — passez MODE=mongo pour installer seulement MongoDB sur un nœud de base de données, passez MODE=rocketchat pour installer seulement l’app Rocket.Chat sur le nœud applicatif. Pour un petit déploiement vous pouvez lancer les deux modes sur chacun des trois nœuds ; pour plus gros, mettez l’app Rocket.Chat sur son propre hôte avec une grappe MongoDB séparée à trois nœuds sur le réseau privé. Le script fait le durcissement de base (SELinux enforcing, fail2ban, dnf-automatic, SSH par clé uniquement), MongoDB 7 du dépôt officiel avec cache WiredTiger dimensionné pour l’hôte, un replica set rs0 authentifié par keyfile, l’install tarball Rocket.Chat officiel avec la version Node.js épinglée, une unité systemd avec LimitNOFILE=64000, nginx qui termine TLS avec les headers d’upgrade WebSocket dont Rocket.Chat a besoin, Let’s Encrypt via certbot, et une boucle d’attente qui plante bruyamment si Rocket.Chat ou le replica set ne montent pas.
#!/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}"
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
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
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}"
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
Rendez-le exécutable et lancez-le. Pour trois nœuds co-locataires :
chmod 700 /root/setup-rocketchat-almalinux9.sh
# rocket01 (candidat primaire)
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 et rocket03 — même env, ajustez NODE_NAME et NODE_IP, MODE=mongo
Après installation sur les trois nœuds, le replica set est initié par le script sur rocket01. Ouvrez https://chat.example.com/ — le premier utilisateur qui s’inscrit devient propriétaire du workspace. Récupérez ce compte immédiatement, puis sous Admin → Workspace → Mobile enrôlez la passerelle push cloud Rocket.Chat pour que les clients mobile en arrière-plan reçoivent les alertes bannière. Le MONGO_OPLOG_URL dans /opt/rocketchat/rocketchat.env est ce qui fait suivre l’oplog à Meteor plutôt que poller — si vous voyez un jour « Falling back to polling » dans le journal rocketchat, c’est cette ligne qui est fausse. Vérifiez que les snapshots VM couvrent /var/lib/mongo sur chaque nœud de base de données ; mongodump est une couche additionnelle utile (restauration point-in-time d’une collection corrompue) mais ce n’est pas un substitut au snapshot du répertoire de données.
Faites tourner ce Rocket.Chat sur le cloud dédié infogéré Stack Harbor avec patching, supervision et escalade Sev-1 inclus — ou réservez un appel découverte si vous avez besoin que le replica set MongoDB soit dimensionné et que la migration depuis un chat SaaS soit planifiée.