Skip to content

Deploying n8n workflow automation on Ubuntu 22.04 (production-ready)

Stand up n8n on Ubuntu 22.04 via Docker Compose with PostgreSQL + queue mode (Redis), nginx + Let's Encrypt, persisted encryption key, webhook URL pinned.

You’ve been asked to stand up n8n for the automation team. The README has you docker run n8nio/n8n against a SQLite database in an anonymous volume, you proxy it through nginx, you hand it over. Eight months later, a routine docker compose down && up -d deletes the anonymous volume — the SQLite database goes with it. Even if the database had survived, the team never saved N8N_ENCRYPTION_KEY, so the credential payloads (Stripe keys, Salesforce OAuth tokens, AWS IAM access keys) are encrypted blobs they can never read again. They restart from zero.

What’s happening

An n8n deployment that is actually production-ready needs more than docker run. PostgreSQL replaces SQLite because workflow execution history grows fast; it sits on the docker network only. The N8N_ENCRYPTION_KEY has to be set explicitly at first boot, persisted to a .env outside the container, and saved to a password manager the moment it’s printed — losing it means every stored credential becomes useless ciphertext. Queue mode (workers separated from the web UI, talking over Redis) is what turns n8n from a hobby tool into a fault-tolerant system. N8N_HOST, WEBHOOK_URL, and N8N_PROTOCOL must be set to the public TLS URL — n8n hands those values to webhook providers, and pointing them at http://localhost is the #1 reason integrations silently fail on first delivery.

How to verify

After install, the listeners should look like this:

ss -lntp | grep -E ':(80|443)\b'
# 0.0.0.0:80   nginx
# 0.0.0.0:443  nginx
# (no 5432, 6379, or 5678 exposed to the host)

Container health:

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

Admin URL through TLS:

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

Encryption key is set inside the running main container (it should never echo back to stdout, just confirm presence):

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

If the worker is Restarting, Redis or the encryption key disagree between main and worker — both must read the same .env.

The fix

Save the script below as /root/setup-n8n-ubuntu22.sh, then run it. It runs base update + UFW + SSH hardening + unattended-upgrades, installs Docker CE, writes /etc/n8n/.env with a generated N8N_ENCRYPTION_KEY plus PostgreSQL credentials, brings up a docker-compose stack (PostgreSQL + Redis + n8n main + n8n worker in queue mode) with no datastore ports exposed, installs nginx + certbot, and polls until the main container answers internally.

#!/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."

Make it executable and run it:

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

First image pull plus initial Postgres migration finishes in 4 to 7 minutes on a 4 vCPU / 8 GB VM. After the script prints the URL, create the owner account through the setup wizard, then go to Settings > Users and disable open signup. The encryption-key warning at the end of the script is not boilerplate — every credential payload in Postgres is encrypted with that single string, and there is no recovery path. Copy it to a password manager the moment the script prints it, verify you can read it back, and only then close the SSH session. The script does not configure host-level backups; pgdata and n8ndata are the stateful volumes, and the assumption is the VM has snapshot/backup at the cloud layer plus the encryption key separately preserved.

Run the production n8n on a Stack Harbor-managed environment with patching cadence, monitoring, and key-rotation runbooks built in: Talk to us about your automation tier →.