Aller au contenu

Déployer Ghost 5.x sur Ubuntu 22.04 (prêt pour la production)

Monter un publisher Ghost 5.x durci sur Ubuntu 22.04 — MySQL 8 en localhost, Ghost-CLI sous utilisateur non-root, nginx + Let's Encrypt, SMTP câblé pour les membres.

On vous a demandé de monter un site Ghost pour l’équipe marketing. Le guide Ghost-CLI est cordial : npm install -g ghost-cli, ghost install, on pointe un DNS sur la machine, on envoie les rédacteurs. Six mois plus tard, le démon Ghost tourne sous root parce que personne n’a lu l’avertissement, MySQL est exposé sur 0.0.0.0:3306 parce que le bind-address par défaut n’a jamais été resserré, le certificat Let’s Encrypt a atteint son 89e jour et le renouvellement a échoué silencieusement parce que l’utilisateur du cron n’avait pas les droits d’écriture sur /etc/letsencrypt, les membres ne peuvent plus se connecter parce que le SMTP sortant n’a jamais été configuré, et l’éditeur s’ouvre sur un écran blanc parce que le journal déborde d’erreurs EACCES.

Ce qui se passe

Un déploiement Ghost réellement prêt pour la production demande plus que ghost install. Ghost doit tourner sous un utilisateur système non-root (ghost est la convention Ghost-CLI) — le démon écoute sur un port haut et passe derrière nginx, donc root n’est jamais requis. MySQL 8 a besoin de bind-address = 127.0.0.1 et d’un rôle dédié ghost avec un mot de passe long et aléatoire, jamais le compte root. nginx termine le TLS devant l’écouteur interne de Ghost sur :2368 avec HSTS et un vrai certificat Let’s Encrypt sur certbot.timer. L’unité systemd émise par Ghost-CLI a besoin de LimitNOFILE=64000 parce que Node garde des sockets ouverts par lecteur actif. Le SMTP doit être câblé avant le premier signup membre, sinon tous les courriels de magic-link partent directement dans le journal comme échecs d’envoi. Aucune de ces étapes n’est individuellement critique — sautez-les et le publisher devient la VM que personne ne possède jusqu’à ce qu’elle casse.

Comment vérifier

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

ss -lntp | grep -E ':(80|443|2368|3306)\b'
# 127.0.0.1:3306   mysqld
# 127.0.0.1:2368   node (ghost)
# 0.0.0.0:80       nginx
# 0.0.0.0:443      nginx

MySQL sur 3306 doit être 127.0.0.1, jamais 0.0.0.0. L’URL admin doit répondre :

curl -I https://votre-domaine-ghost/ghost/
# HTTP/2 200

MySQL doit être joignable pour le healthcheck de Ghost :

mysqladmin -uroot ping
# mysqld is alive

Si MySQL écoute sur 0.0.0.0, le périmètre est grand ouvert. Si l’URL admin renvoie 502, le processus Node est mort sur une dérive de configuration et l’unité systemd boucle en restart.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-ghost-ubuntu22.sh, puis exécutez-le. Il déroule l’installation complète sur une VM Ubuntu 22.04 fraîche : mise à jour de base, ajustement noyau/réseau, limites de fichiers, UFW (SSH + HTTP + HTTPS uniquement), durcissement SSH avec clé root préservée, unattended-upgrades pour les correctifs de sécurité, MySQL 8 avec bind-address = 127.0.0.1 et un rôle dédié ghost, Node.js 18 LTS via NodeSource, le module ghost-cli en global, un utilisateur système dédié ghost-mgr (l’exigence stricte de Ghost-CLI : root ne doit pas posséder /var/www/ghost), le flux d’installation scripté avec --no-prompt, une unité systemd émise par Ghost-CLI avec LimitNOFILE=64000, nginx avec TLS terminé par Let’s Encrypt, une strophe SMTP câblée dans config.production.json, et une boucle de sondage qui attend que :2368 et :443 répondent avant de déclarer le succès.

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

### Ubuntu 22.04 Ghost 5.x clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures MySQL 8 + Ghost 5.x + nginx + Let's Encrypt
### Wires SMTP for member magic-link delivery
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${GHOST_DOMAIN:?Set GHOST_DOMAIN=blog.example.com}"
: "${GHOST_EMAIL:?Set GHOST_EMAIL=ops@example.com for Let's Encrypt}"
: "${SMTP_HOST:?Set SMTP_HOST, e.g. smtp.mailgun.org}"
: "${SMTP_USER:?Set SMTP_USER}"
: "${SMTP_PASS:?Set SMTP_PASS}"
SMTP_PORT="${SMTP_PORT:-587}"
SMTP_FROM="${SMTP_FROM:-noreply@${GHOST_DOMAIN#*.}}"
GHOST_DB_PASSWORD="${GHOST_DB_PASSWORD:-$(openssl rand -hex 24)}"
NODE_MAJOR=18

echo
echo "========================================"
echo "Ghost Ubuntu 22.04 Setup"
echo "Domain: ${GHOST_DOMAIN}"
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 \
  iproute2 net-tools openssl \
  software-properties-common build-essential

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

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-ghost.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

net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_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-ghost.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 SSH 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"
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

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 MySQL 8"
apt-get -y install mysql-server

echo "==> Locking MySQL to localhost"
cat > /etc/mysql/mysql.conf.d/zz-ghost.cnf <<'MYSQL'
[mysqld]
bind-address = 127.0.0.1
mysqlx-bind-address = 127.0.0.1
default-authentication-plugin = mysql_native_password
max_connections = 200
MYSQL

systemctl restart mysql

echo "==> Creating Ghost database and role"
mysql --protocol=socket -uroot <<SQL
CREATE DATABASE IF NOT EXISTS ghost_prod CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'ghost'@'127.0.0.1' IDENTIFIED WITH mysql_native_password BY '${GHOST_DB_PASSWORD}';
ALTER USER 'ghost'@'127.0.0.1' IDENTIFIED WITH mysql_native_password BY '${GHOST_DB_PASSWORD}';
GRANT ALL PRIVILEGES ON ghost_prod.* TO 'ghost'@'127.0.0.1';
FLUSH PRIVILEGES;
SQL

echo "==> Installing Node.js ${NODE_MAJOR} LTS"
curl -fsSL https://deb.nodesource.com/setup_${NODE_MAJOR}.x | bash -
apt-get -y install nodejs

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

echo "==> Installing Ghost-CLI globally"
npm install -g ghost-cli@latest

echo "==> Creating ghost-mgr system user (Ghost-CLI requires non-root owner)"
if ! id -u ghost-mgr >/dev/null 2>&1; then
  useradd --create-home --shell /bin/bash --user-group ghost-mgr
  usermod -aG sudo ghost-mgr
fi

echo "==> Preparing /var/www/ghost"
mkdir -p /var/www/ghost
chown ghost-mgr:ghost-mgr /var/www/ghost
chmod 775 /var/www/ghost

echo "==> Running Ghost install as ghost-mgr"
sudo -i -u ghost-mgr bash <<INSTALL
set -euo pipefail
cd /var/www/ghost
ghost install \
  --no-prompt \
  --db mysql \
  --dbhost 127.0.0.1 \
  --dbuser ghost \
  --dbpass '${GHOST_DB_PASSWORD}' \
  --dbname ghost_prod \
  --url https://${GHOST_DOMAIN} \
  --port 2368 \
  --process systemd \
  --no-setup-nginx \
  --no-setup-ssl \
  --no-setup-mysql \
  --no-stack \
  --mail SMTP \
  --mailservice "" \
  --mailuser "${SMTP_USER}" \
  --mailpass "${SMTP_PASS}" \
  --mailhost "${SMTP_HOST}" \
  --mailport "${SMTP_PORT}" \
  --mailsecure false \
  --mailfrom "${SMTP_FROM}" \
  --start false
INSTALL

echo "==> Hardening config.production.json permissions"
chmod 600 /var/www/ghost/config.production.json || true
chown ghost-mgr:ghost-mgr /var/www/ghost/config.production.json || true

echo "==> Raising LimitNOFILE on the Ghost systemd unit"
GHOST_UNIT="$(systemctl list-unit-files 'ghost_*' --no-legend | awk '{print $1}' | head -n1)"
if [[ -n "${GHOST_UNIT}" ]]; then
  mkdir -p "/etc/systemd/system/${GHOST_UNIT}.d"
  cat > "/etc/systemd/system/${GHOST_UNIT}.d/override.conf" <<'GHOST_LIMITS'
[Service]
LimitNOFILE=64000
GHOST_LIMITS
  systemctl daemon-reload
fi

echo "==> Starting Ghost"
sudo -i -u ghost-mgr bash -lc "cd /var/www/ghost && ghost start"

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

if ! ss -lntp | grep -q '127.0.0.1:2368'; then
  echo "Ghost failed to listen on 127.0.0.1:2368"
  sudo -i -u ghost-mgr bash -lc "cd /var/www/ghost && ghost log -n 200" || true
  exit 1
fi

echo "==> Writing nginx vhost"
cat > /etc/nginx/sites-available/ghost <<NGINX
upstream ghost_backend {
    server 127.0.0.1:2368;
    keepalive 32;
}

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

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

    client_max_body_size 50M;
    proxy_read_timeout   120s;
    proxy_send_timeout   120s;

    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_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_http_version 1.1;
        proxy_pass http://ghost_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/ghost /etc/nginx/sites-enabled/ghost
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 "${GHOST_EMAIL}" -d "${GHOST_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 "SSH effective settings:"
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication) ' || true

echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|2368|3306)\b' || true

echo
echo "Services:"
systemctl is-active mysql nginx fail2ban chrony || true
systemctl is-active "${GHOST_UNIT:-ghost}" || true

echo
echo "Ghost DB password (record this somewhere safe):"
echo "${GHOST_DB_PASSWORD}"

echo
echo "Admin URL:"
echo "https://${GHOST_DOMAIN}/ghost/"

echo
echo "Final step:"
echo "Open the admin URL, create the first Owner account, then send a test member email to verify SMTP."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-ghost-ubuntu22.sh
GHOST_DOMAIN=blog.example.com \
GHOST_EMAIL=ops@example.com \
SMTP_HOST=smtp.mailgun.org \
SMTP_USER=postmaster@mg.example.com \
SMTP_PASS='REMPLACER' \
/root/setup-ghost-ubuntu22.sh

La plupart des installations se terminent en 6 à 10 minutes sur une VM 2 vCPU / 4 Go. Le premier compte créé via /ghost/ devient l’Owner — faites-le immédiatement après que le script affiche l’URL admin, puis envoyez un courriel test de magic-link à un membre pour confirmer que la strophe SMTP livre réellement avant de migrer la moindre liste d’abonnés. Le script n’active volontairement pas de sauvegardes au niveau hôte ; mysqldump ghost_prod plus /var/www/ghost/content/ doivent être couverts par votre politique d’instantanés VM.

Faites tourner le Ghost de production sur un environnement infogéré Stack Harbor avec cadence de patching, supervision et escalade Sev-1 en place : voir Cloud PaaS → et le gabarit publisher WordPress entreprise →.