Aller au contenu

Déployer n8n (automatisation de flux) sur Ubuntu 22.04 (prêt pour la production)

Monter n8n sur Ubuntu 22.04 via Docker Compose avec PostgreSQL + mode file (Redis), nginx + Let's Encrypt, clé de chiffrement persistée, URL webhook fixée.

On vous demande de monter n8n pour l’équipe d’automatisation. Le README vous fait lancer docker run n8nio/n8n contre une base SQLite dans un volume anonyme, vous mettez ça derrière un proxy nginx, vous remettez à l’équipe. Huit mois plus tard, un docker compose down && up -d de routine supprime le volume anonyme — la base SQLite part avec. Même si la base avait survécu, l’équipe n’a jamais sauvegardé N8N_ENCRYPTION_KEY, donc les charges utiles d’identifiants (clés Stripe, jetons OAuth Salesforce, clés IAM AWS) sont des blobs chiffrés qu’ils ne peuvent plus jamais lire. Ils repartent de zéro.

Ce qui se passe

Un déploiement n8n réellement prêt pour la production demande plus que docker run. PostgreSQL remplace SQLite parce que l’historique d’exécution des flux croît vite ; il reste sur le réseau docker uniquement. La N8N_ENCRYPTION_KEY doit être définie explicitement au premier démarrage, persistée dans un .env à l’extérieur du conteneur, et sauvegardée dans un gestionnaire de mots de passe dès l’instant où elle s’affiche — la perdre signifie que chaque identifiant stocké devient un texte chiffré inutile. Le mode file (workers séparés de l’interface web, communiquant par Redis) est ce qui transforme n8n d’outil de loisir en système tolérant aux pannes. N8N_HOST, WEBHOOK_URL et N8N_PROTOCOL doivent être réglés sur l’URL TLS publique — n8n remet ces valeurs aux fournisseurs de webhooks, et les pointer vers http://localhost est la cause numéro un des intégrations qui échouent silencieusement à la première livraison.

Comment vérifier

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

ss -lntp | grep -E ':(80|443)\b'
# 0.0.0.0:80   nginx
# 0.0.0.0:443  nginx
# (pas de 5432, 6379 ou 5678 exposés à l'hôte)

État des conteneurs :

cd /opt/n8n && docker compose ps --format 'table {{.Name}}\t{{.Status}}'
# n8n-postgres-1   Up (healthy)
# n8n-redis-1      Up (healthy)
# n8n-main-1       Up (healthy)
# n8n-worker-1     Up

URL d’administration en TLS :

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

La clé de chiffrement est réglée à l’intérieur du conteneur principal en marche (elle ne doit jamais sortir vers stdout, on confirme juste la présence) :

docker exec n8n-main-1 sh -c 'test -n "$N8N_ENCRYPTION_KEY" && echo present || echo missing'
# present

Si le worker est en Restarting, Redis ou la clé de chiffrement ne s’accordent pas entre main et worker — les deux doivent lire le même .env.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-n8n-ubuntu22.sh, puis exécutez-le. Il déroule mise à jour de base + UFW + durcissement SSH + unattended-upgrades, installe Docker CE, écrit /etc/n8n/.env avec une N8N_ENCRYPTION_KEY générée plus les identifiants PostgreSQL, monte la pile docker-compose (PostgreSQL + Redis + n8n main + n8n worker en mode file) sans port de magasin exposé, installe nginx + certbot, et sonde jusqu’à ce que le conteneur principal réponde en interne.

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

### Ubuntu 22.04 n8n clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs Docker CE + n8n (PostgreSQL backend, queue mode w/ Redis) + nginx + Let's Encrypt
### Datastores bound to docker network only
### Persists N8N_ENCRYPTION_KEY to /etc/n8n/.env at 600 — save it to your password manager
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${N8N_DOMAIN:?Set N8N_DOMAIN=n8n.example.com}"
: "${N8N_EMAIL:?Set N8N_EMAIL=ops@example.com for Let's Encrypt}"

N8N_VERSION="${N8N_VERSION:-1.62.4}"
PG_PASS="$(openssl rand -hex 24)"
N8N_ENCRYPTION_KEY="$(openssl rand -hex 32)"

echo
echo "========================================"
echo "n8n Ubuntu 22.04 Setup"
echo "Domain: ${N8N_DOMAIN}"
echo "Version: ${N8N_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 \
  software-properties-common

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

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-n8n.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
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-n8n.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"
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 Docker CE"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
  gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg

echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
  https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
  > /etc/apt/sources.list.d/docker.list

apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io \
  docker-buildx-plugin docker-compose-plugin

systemctl enable --now docker

echo "==> Writing /etc/n8n/.env"
mkdir -p /etc/n8n
cat > /etc/n8n/.env <<ENV
N8N_VERSION=${N8N_VERSION}

N8N_HOST=${N8N_DOMAIN}
N8N_PROTOCOL=https
N8N_PORT=5678
WEBHOOK_URL=https://${N8N_DOMAIN}/
N8N_EDITOR_BASE_URL=https://${N8N_DOMAIN}/

N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}

EXECUTIONS_MODE=queue
QUEUE_BULL_REDIS_HOST=n8n-redis
QUEUE_BULL_REDIS_PORT=6379

DB_TYPE=postgresdb
DB_POSTGRESDB_HOST=n8n-postgres
DB_POSTGRESDB_PORT=5432
DB_POSTGRESDB_DATABASE=n8n
DB_POSTGRESDB_USER=n8n
DB_POSTGRESDB_PASSWORD=${PG_PASS}

POSTGRES_USER=n8n
POSTGRES_PASSWORD=${PG_PASS}
POSTGRES_DB=n8n
PGDATA=/var/lib/postgresql/data

N8N_RUNNERS_ENABLED=true
N8N_DISABLE_PRODUCTION_MAIN_PROCESS=false
N8N_LOG_LEVEL=info
N8N_DIAGNOSTICS_ENABLED=false
N8N_VERSION_NOTIFICATIONS_ENABLED=true

GENERIC_TIMEZONE=America/Toronto
TZ=America/Toronto
ENV
chmod 600 /etc/n8n/.env
chown root:root /etc/n8n/.env

echo "==> Writing docker-compose.yml at /opt/n8n"
mkdir -p /opt/n8n
ln -sf /etc/n8n/.env /opt/n8n/.env

cat > /opt/n8n/docker-compose.yml <<'COMPOSE'
name: n8n

x-app-env: &app-env
  env_file:
    - .env

services:
  n8n-postgres:
    image: postgres:16.4-alpine
    container_name: n8n-postgres
    restart: unless-stopped
    <<: *app-env
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 6

  n8n-redis:
    image: redis:7.4-alpine
    container_name: n8n-redis
    restart: unless-stopped
    volumes:
      - redisdata:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 6

  n8n-main:
    image: docker.n8n.io/n8nio/n8n:${N8N_VERSION}
    container_name: n8n-main
    restart: unless-stopped
    <<: *app-env
    command: ["start"]
    ports:
      - "127.0.0.1:5678:5678"
    volumes:
      - n8ndata:/home/node/.n8n
    depends_on:
      n8n-postgres:
        condition: service_healthy
      n8n-redis:
        condition: service_healthy
    healthcheck:
      test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:5678/healthz || exit 1"]
      interval: 15s
      timeout: 10s
      retries: 8

  n8n-worker:
    image: docker.n8n.io/n8nio/n8n:${N8N_VERSION}
    container_name: n8n-worker
    restart: unless-stopped
    <<: *app-env
    command: ["worker"]
    volumes:
      - n8ndata:/home/node/.n8n
    depends_on:
      n8n-main:
        condition: service_healthy

volumes:
  pgdata:
  redisdata:
  n8ndata:
COMPOSE

chmod 640 /opt/n8n/docker-compose.yml

echo "==> docker compose pull + up -d"
cd /opt/n8n
docker compose pull
docker compose up -d

echo "==> Waiting for n8n main to answer on 127.0.0.1:5678"
for i in {1..120}; do
  if curl -sf -o /dev/null http://127.0.0.1:5678/healthz; then
    break
  fi
  sleep 2
done

if ! curl -sf -o /dev/null http://127.0.0.1:5678/healthz; then
  echo "n8n main did not respond on 127.0.0.1:5678"
  docker compose ps
  docker compose logs --tail 200 n8n-main n8n-worker || true
  exit 1
fi

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

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

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

    client_max_body_size 50M;
    proxy_read_timeout 600s;
    proxy_send_timeout 600s;

    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://127.0.0.1:5678;
        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 https;
        proxy_cache_bypass \$http_upgrade;
    }
}
NGINX

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

certbot --nginx --non-interactive --agree-tos \
  -m "${N8N_EMAIL}" -d "${N8N_DOMAIN}" --redirect

systemctl enable --now certbot.timer

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

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "Services:"
systemctl is-active docker nginx fail2ban chrony || true
echo
echo "Compose status:"
cd /opt/n8n && docker compose ps --format 'table {{.Name}}\t{{.Status}}'
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443)\b' || true
echo
echo "Web UI:"
echo "https://${N8N_DOMAIN}/"
echo
echo "Credentials (record to your password manager NOW):"
echo "  POSTGRES_PASSWORD: ${PG_PASS}"
echo
echo "================================================================"
echo "  CRITICAL — SAVE THIS NOW. SAVE THIS NOW. SAVE THIS NOW."
echo "================================================================"
echo "  N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY}"
echo
echo "  Every Stripe key, Salesforce token, AWS secret, OAuth refresh"
echo "  token, and webhook secret your workflows ever store is"
echo "  encrypted with this exact string. The credential rows in"
echo "  Postgres are useless ciphertext without it."
echo
echo "  Lose this key and you lose the ability to decrypt every"
echo "  credential payload in your n8n install. There is no recovery."
echo "  n8n will not regenerate it. You start the credentials over."
echo
echo "  Copy it to your password manager (1Password, Bitwarden,"
echo "  Vaultwarden) RIGHT NOW, in the same vault entry as the"
echo "  POSTGRES_PASSWORD. Verify you can read it back before you"
echo "  close this SSH session."
echo "================================================================"
echo
echo "Final step:"
echo "Open the URL, create the owner account through the setup wizard, then go to Settings > Users and disable open signup."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-n8n-ubuntu22.sh
N8N_DOMAIN=n8n.example.com N8N_EMAIL=ops@example.com /root/setup-n8n-ubuntu22.sh

Le premier téléchargement d’images plus la migration initiale Postgres se termine en 4 à 7 minutes sur une VM 4 vCPU / 8 Go. Une fois que le script affiche l’URL, créez le compte propriétaire via le gabarit de configuration, puis allez dans Paramètres > Utilisateurs et désactivez les inscriptions ouvertes. L’avertissement sur la clé de chiffrement à la fin du script n’est pas un cliché — chaque charge utile d’identifiants dans Postgres est chiffrée avec cette seule chaîne, et il n’y a aucune voie de récupération. Copiez-la dans un gestionnaire de mots de passe à l’instant où le script l’affiche, vérifiez que vous pouvez la relire, et seulement après fermez la session SSH. Le script n’active volontairement pas de sauvegardes au niveau hôte ; pgdata et n8ndata sont les volumes persistants, et l’hypothèse de base reste que la VM bénéficie d’un instantané/sauvegarde au niveau infonuagique plus la clé de chiffrement préservée séparément.

Faites tourner le n8n de production sur un environnement infogéré Stack Harbor avec cadence de patching, supervision et procédures de rotation de clés intégrées : Parlons de votre étage d’automatisation →.