Aller au contenu

Déployer Cal.com (planification) sur Ubuntu 22.04 (prêt pour la production)

Monter un Cal.com durci sur Ubuntu 22.04 — PostgreSQL en localhost, nginx + Let's Encrypt, OAuth calendrier, courriels de confirmation, cycle systemd.

On vous demande de monter une alternative auto-hébergée à Calendly pour l’équipe des ventes. Le README de Cal.com vous guide à travers git clone, yarn, yarn dev, vous mettez ça derrière un proxy inverse trouvé sous la main, vous remettez le tout à l’équipe. Trois mois plus tard, PostgreSQL répond sur 0.0.0.0:5432 parce que personne n’a restreint listen_addresses, le client OAuth Google Calendar a été créé contre http://localhost:3000 et donc le flot de consentement boucle en production, les courriels de confirmation tombent en pourriels parce que le bloc SMTP dans .env n’a jamais été rempli, et le processus Node tourne sous yarn dev à l’intérieur d’un tmux qui est mort avec la session SSH.

Ce qui se passe

Un déploiement Cal.com réellement prêt pour la production demande plus que yarn dev. PostgreSQL doit être lié à 127.0.0.1 uniquement ; la version Next.js de production (yarn build puis yarn start) tourne sous une unité systemd avec LimitNOFILE=64000 et Restart=always ; nginx termine le TLS devant :3000 avec HSTS et un vrai certificat Let’s Encrypt sur son minuteur de renouvellement ; les clients OAuth de calendrier (Google Workspace, Microsoft 365) sont enregistrés contre la véritable URI de redirection https:// de production, jamais localhost ; les identifiants SMTP vivent dans /etc/cal/.env en mode 600 parce que les courriels de confirmation sont toute la boucle produit ; et les secrets NEXTAUTH_SECRET et CALENDSO_ENCRYPTION_KEY sont générés une fois et sauvegardés dans un gestionnaire de mots de passe parce que les faire tourner invalide chaque jeton tiers stocké.

Comment vérifier

Après installation, les écouteurs doivent ressembler à ça :

ss -lntp | grep -E ':(80|443|3000|5432)\b'
# 127.0.0.1:3000   node (cal.com)
# 127.0.0.1:5432   postgres
# 0.0.0.0:80       nginx
# 0.0.0.0:443      nginx

PostgreSQL sur 5432 doit être 127.0.0.1, jamais 0.0.0.0. Confirmez que l’URL d’administration répond en TLS :

curl -I https://cal.example.com/
# HTTP/2 200
# strict-transport-security: max-age=31536000; includeSubDomains

Connectivité BD depuis le compte applicatif :

sudo -u cal psql "$(grep ^DATABASE_URL /etc/cal/.env | cut -d= -f2- | tr -d '\"')" -c '\dt' | head

Si psql retourne la liste des tables Prisma, la clé de chiffrement, l’URL de la BD et les migrations s’alignent. S’il échoue avec password authentication failed, le .env et le mot de passe du rôle ont dérivé.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-cal-ubuntu22.sh, puis exécutez-le. Il déroule mise à jour de base + UFW + durcissement SSH + unattended-upgrades, installe PostgreSQL 14 lié à localhost et Node 20 LTS, crée un utilisateur système cal avec un clone de calcom/cal.com sur une étiquette épinglée, lance yarn install + yarn build, écrit /etc/cal/.env avec chaque secret requis, installe une unité systemd sur 127.0.0.1:3000 avec LimitNOFILE=64000, puis nginx + certbot, en sondant jusqu’à ce que :3000 et :443 répondent.

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

### Ubuntu 22.04 Cal.com clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures PostgreSQL + Cal.com (Next.js) + nginx + Let's Encrypt
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${CAL_DOMAIN:?Set CAL_DOMAIN=cal.example.com}"
: "${CAL_EMAIL:?Set CAL_EMAIL=ops@example.com for Let's Encrypt}"
: "${SMTP_HOST:?Set SMTP_HOST=smtp.example.com}"
: "${SMTP_USER:?Set SMTP_USER=cal@example.com}"
: "${SMTP_PASS:?Set SMTP_PASS=app-password}"

CAL_VERSION="${CAL_VERSION:-v4.5.0}"
DB_NAME="calcom"
DB_USER="calcom"
DB_PASS="$(openssl rand -hex 24)"
NEXTAUTH_SECRET="$(openssl rand -hex 32)"
CALENDSO_ENCRYPTION_KEY="$(openssl rand -hex 24)"

echo
echo "========================================"
echo "Cal.com Ubuntu 22.04 Setup"
echo "Domain: ${CAL_DOMAIN}"
echo "Version: ${CAL_VERSION}"
echo "========================================"
echo

echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  vim curl wget ca-certificates gnupg2 \
  chrony fail2ban unattended-upgrades \
  ufw lsof tcpdump dnsutils tar gzip git \
  iproute2 net-tools openssl build-essential \
  software-properties-common python3

echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-cal.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.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535

net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
SYSCTL

modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-cal.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS

echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo "==> Hardening SSH while keeping root key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)

set_sshd_option() {
  local key="$1"
  local value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}

set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option ChallengeResponseAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4

sshd -t
systemctl restart ssh

echo "==> Configuring fail2ban"
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 "==> Configuring unattended-upgrades for security"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPG

echo "==> Installing PostgreSQL 14"
apt-get -y install postgresql postgresql-contrib

echo "==> Locking PostgreSQL to localhost"
PG_CONF="/etc/postgresql/14/main/postgresql.conf"
sed -i "s|^#*listen_addresses.*|listen_addresses = 'localhost'|" "$PG_CONF"
systemctl restart postgresql

echo "==> Creating Cal.com database and role"
sudo -u postgres psql -v ON_ERROR_STOP=1 <<SQL
DO \$\$
BEGIN
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${DB_USER}') THEN
    CREATE ROLE ${DB_USER} LOGIN PASSWORD '${DB_PASS}';
  ELSE
    ALTER ROLE ${DB_USER} WITH PASSWORD '${DB_PASS}';
  END IF;
END
\$\$;
SQL
sudo -u postgres psql -tc "SELECT 1 FROM pg_database WHERE datname='${DB_NAME}'" | grep -q 1 \
  || sudo -u postgres createdb -O ${DB_USER} ${DB_NAME}

echo "==> Installing Node 20 LTS via NodeSource"
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get -y install nodejs
corepack enable
corepack prepare yarn@stable --activate

echo "==> Creating cal system user"
if ! id -u cal >/dev/null 2>&1; then
  useradd --system --create-home --home-dir /opt/cal --shell /bin/bash cal
fi

echo "==> Cloning Cal.com ${CAL_VERSION}"
sudo -u cal git clone --depth 1 --branch "${CAL_VERSION}" \
  https://github.com/calcom/cal.com.git /opt/cal/app || true
cd /opt/cal/app
sudo -u cal git fetch --depth 1 origin "${CAL_VERSION}"
sudo -u cal git checkout "${CAL_VERSION}"

echo "==> Writing /etc/cal/.env"
mkdir -p /etc/cal
cat > /etc/cal/.env <<ENV
NEXT_PUBLIC_WEBAPP_URL=https://${CAL_DOMAIN}
NEXTAUTH_URL=https://${CAL_DOMAIN}
NEXTAUTH_SECRET=${NEXTAUTH_SECRET}
CALENDSO_ENCRYPTION_KEY=${CALENDSO_ENCRYPTION_KEY}

DATABASE_URL="postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}"
DATABASE_DIRECT_URL="postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}"

EMAIL_FROM=noreply@${CAL_DOMAIN}
EMAIL_SERVER_HOST=${SMTP_HOST}
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=${SMTP_USER}
EMAIL_SERVER_PASSWORD=${SMTP_PASS}

NEXT_PUBLIC_TELEMETRY_KEY=
CALCOM_TELEMETRY_DISABLED=1

GOOGLE_API_CREDENTIALS=
MS_GRAPH_CLIENT_ID=
MS_GRAPH_CLIENT_SECRET=

NODE_ENV=production
PORT=3000
ENV
chown -R root:cal /etc/cal
chmod 750 /etc/cal
chmod 640 /etc/cal/.env

ln -sf /etc/cal/.env /opt/cal/app/.env
chown -h cal:cal /opt/cal/app/.env

echo "==> Installing dependencies (this can take 10+ minutes)"
cd /opt/cal/app
sudo -u cal yarn install --frozen-lockfile

echo "==> Running database migrations"
sudo -u cal yarn workspace @calcom/prisma db-deploy

echo "==> Building Cal.com"
sudo -u cal yarn build

echo "==> Writing systemd unit"
cat > /etc/systemd/system/cal.service <<'UNIT'
[Unit]
Description=Cal.com scheduling
After=network.target postgresql.service
Requires=postgresql.service

[Service]
Type=simple
User=cal
Group=cal
WorkingDirectory=/opt/cal/app
EnvironmentFile=/etc/cal/.env
ExecStart=/usr/bin/yarn start
Restart=always
RestartSec=10
LimitNOFILE=64000
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now cal

echo "==> Waiting for Cal.com to listen on 127.0.0.1:3000"
for i in {1..90}; do
  if ss -lntp | grep -q '127.0.0.1:3000'; then
    break
  fi
  sleep 1
done

if ! ss -lntp | grep -q '127.0.0.1:3000'; then
  echo "Cal.com failed to bind on 127.0.0.1:3000"
  journalctl -u cal -n 200 --no-pager || true
  exit 1
fi

echo "==> Installing nginx and certbot"
apt-get -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/cal <<NGINX
server {
    listen 80;
    listen [::]:80;
    server_name ${CAL_DOMAIN};
    return 301 https://\$host\$request_uri;
}

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

    client_max_body_size 25M;
    proxy_read_timeout 300s;
    proxy_send_timeout 300s;

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

    location / {
        proxy_pass http://127.0.0.1:3000;
        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 https;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}
NGINX

ln -sf /etc/nginx/sites-available/cal /etc/nginx/sites-enabled/cal
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable --now nginx
systemctl reload nginx

echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
  -m "${CAL_EMAIL}" -d "${CAL_DOMAIN}" --redirect

systemctl enable --now certbot.timer

echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
  if ss -lntp | grep -q ':443'; then
    break
  fi
  sleep 1
done

echo "==> Final package update"
apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "Services:"
systemctl is-active postgresql cal nginx fail2ban chrony || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|3000|5432)\b' || true
echo
echo "Web UI:"
echo "https://${CAL_DOMAIN}/"
echo
echo "Credentials (record to your password manager NOW):"
echo "  DB user:     ${DB_USER}"
echo "  DB password: ${DB_PASS}"
echo "  NEXTAUTH_SECRET:         ${NEXTAUTH_SECRET}"
echo "  CALENDSO_ENCRYPTION_KEY: ${CALENDSO_ENCRYPTION_KEY}"
echo
echo "Calendar OAuth (manual, post-install):"
echo "  Google: create OAuth client in Google Cloud Console with redirect"
echo "    https://${CAL_DOMAIN}/api/integrations/googlecalendar/callback"
echo "    then paste the JSON into GOOGLE_API_CREDENTIALS in /etc/cal/.env"
echo "  Microsoft: register app in Entra ID with redirect"
echo "    https://${CAL_DOMAIN}/api/integrations/office365calendar/callback"
echo "    set MS_GRAPH_CLIENT_ID and MS_GRAPH_CLIENT_SECRET"
echo "  Then: systemctl restart cal"
echo
echo "Final step:"
echo "Open the URL, complete the first-admin wizard, then disable open signup in Admin > Settings."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-cal-ubuntu22.sh
CAL_DOMAIN=cal.example.com CAL_EMAIL=ops@example.com \
  SMTP_HOST=smtp.example.com SMTP_USER=cal@example.com SMTP_PASS=app-password \
  /root/setup-cal-ubuntu22.sh

Le premier yarn install plus yarn build est le poste qui prend le plus de temps — 12 à 20 minutes sur une VM 4 vCPU / 8 Go. Une fois que le script affiche l’URL, complétez le gabarit du premier admin (cet usager devient propriétaire), puis allez dans Admin > Paramètres et fermez les inscriptions ouvertes. Les clients OAuth doivent être enregistrés manuellement contre les URI de redirection de production affichées à la fin — coller localhost dans l’un ou l’autre est la cause numéro un des bascules de consentement qui bouclent en production. Le script n’active volontairement pas de sauvegardes au niveau hôte ; pg_dump calcom plus /etc/cal/.env sont les seuls chemins persistants et l’hypothèse de base reste que la VM bénéficie d’un instantané/sauvegarde au niveau infonuagique.

Faites tourner le Cal.com de production sur un environnement infogéré Stack Harbor avec cadence de patching, supervision et escalade d’astreinte intégrées : Environnements infogérés (Environnements infogérés) →.