Self-Hosting & VPS•

How to Self-Host n8n with Docker on a VPS: Production Blueprint (2026)

Step-by-step production guide to self-hosting n8n with Docker Compose, PostgreSQL, and Caddy automatic SSL on Ubuntu. Includes hardware sizing, OOM fixes, and backup scripts.

By Andres Lechuga · Systems Architecture & Automation
Affiliate Disclosure

To self-host n8n in production, deploy n8n alongside PostgreSQL 16 and Caddy (for automatic Let’s Encrypt HTTPS) via Docker Compose on an Ubuntu 24.04 VPS with at least 2 vCPUs and 4 GB of RAM (~$6.99–$12/month), unlocking unlimited workflow executions with full data sovereignty. Avoid single-container SQLite setups and 1 GB RAM servers, which fail under concurrent webhook loads and memory spikes.

If you have already compared per-credit SaaS pricing in our n8n vs Make breakdown or modeled your monthly volume in the n8n Self-Hosting ROI Calculator, you know that self-hosting eliminates recurring automation taxes. However, most self-hosted outages happen because of four avoidable infrastructure mistakes: exposing port 5678 without TLS, running on SQLite, forgetting EXECUTIONS_DATA_PRUNE, or losing the N8N_ENCRYPTION_KEY.


1. Hardware Sizing: Choosing the Right VPS Tier

An idle n8n instance consumes roughly 250 MB to 400 MB of RAM, but Node.js V8 heap usage spikes rapidly when parsing multi-megabyte JSON arrays or orchestrating LLM chains. Always size your server for your 6-month projected throughput rather than day-one testing:

Workload Tier Monthly Executions Recommended Specs Database Backend Est. VPS Cost
Sandbox / Personal < 10,000 runs/mo 1 vCPU · 2 GB RAM · 25 GB NVMe SQLite or Postgres ~$4.99 – $6/mo
Production Sweet Spot 10,000 – 150,000 runs/mo 2 vCPU · 4 GB RAM · 50 GB NVMe PostgreSQL 16 ~$6.99 – $12/mo
High-Throughput / AI ETL 150,000 – 500,000+ runs/mo 4–8 vCPU · 8–16 GB RAM · 100 GB NVMe Postgres + Redis Queue ~$15 – $25/mo

(Need help comparing KVM latency and NVMe benchmarks across providers? See our upcoming Best VPS Hosting for n8n benchmark guide.)


2. Step 1: Server Hardening, Swap & Firewall (Ubuntu 24.04)

Before installing Docker, point an A record in your DNS provider (e.g., Cloudflare or Namecheap) from n8n.yourdomain.com to your VPS public IPv4 address. If using Cloudflare, keep the proxy disabled (gray cloud) until Caddy issues your initial TLS certificate.

Log into your fresh Ubuntu server via SSH and apply baseline security and swap memory protection:

# 1. Update system packages and install essentials
sudo apt update && sudo apt upgrade -y
sudo apt install -y ufw fail2ban curl

# 2. Configure 4GB swap file to prevent Linux OOM kills during payload spikes
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo sysctl -w vm.swappiness=10

# 3. Lock down firewall: allow ONLY SSH, HTTP, and HTTPS
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw --force enable

Next, install the official Docker Engine and Docker Compose plugin:

curl -fsSL [https://get.docker.com](https://get.docker.com) | sudo sh
sudo usermod -aG docker $USER
newgrp docker

# Verify installation
docker --version
docker compose version

3. Step 2: Production Docker Compose Stack (n8n + Postgres + Caddy)

Create an isolated directory under /opt/n8n so your configuration, environment secrets, and reverse-proxy files remain organized and easy to back up:

sudo mkdir -p /opt/n8n && sudo chown -R $USER:$USER /opt/n8n
cd /opt/n8n

Generate Cryptographic Secrets (.env)

Never hardcode passwords or encryption keys inside docker-compose.yml. Generate a permanent 32-byte encryption key and database password inside a locked .env file:

cat > .env <<EOF -hex .env 24) 32) 600 DOMAIN_NAME="n8n.yourdomain.com" EOF GENERIC_TIMEZONE="UTC" N8N_ENCRYPTION_KEY="$(openssl" POSTGRES_DB="n8n_production" POSTGRES_PASSWORD="$(openssl" POSTGRES_USER="n8n_prod" ``` chmod rand> **Critical Warning:** Copy the generated `N8N_ENCRYPTION_KEY` from `.env` into an offline password manager immediately. n8n uses this key to encrypt every API token and OAuth credential stored in PostgreSQL. If you rebuild your server without this exact string, every saved credential becomes permanently unreadable.

### Create the `Caddyfile`

Caddy automatically obtains and renews Let's Encrypt SSL certificates and natively proxies WebSocket connections required by the n8n visual editor:

```caddyfile
{$DOMAIN_NAME} {
    reverse_proxy n8n:5678
}

Create docker-compose.yml

This configuration binds n8n strictly to the internal Docker network (expose: "5678" instead of public ports), configures PostgreSQL 16 health checks, caps V8 heap memory safely below the 4 GB host ceiling, and enables automatic 7-day execution log pruning:

services:
  postgres:
    image: postgres:16-alpine
    container_name: n8n-postgres
    restart: unless-stopped
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 5s
      timeout: 5s
      retries: 10
    networks:
      - n8n_internal

  n8n:
    image: docker.n8n.io/n8nio/n8n:latest
    container_name: n8n-app
    restart: unless-stopped
    expose:
      - "5678"
    environment:
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=postgres
      - DB_POSTGRESDB_PORT=5432
      - DB_POSTGRESDB_DATABASE=${POSTGRES_DB}
      - DB_POSTGRESDB_USER=${POSTGRES_USER}
      - DB_POSTGRESDB_PASSWORD=${POSTGRES_PASSWORD}
      - N8N_HOST=${DOMAIN_NAME}
      - N8N_PORT=5678
      - N8N_PROTOCOL=https
      - NODE_ENV=production
      - WEBHOOK_URL=https://${DOMAIN_NAME}/
      - GENERIC_TIMEZONE=${GENERIC_TIMEZONE}
      - TZ=${GENERIC_TIMEZONE}
      - N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}
      - N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true
      - EXECUTIONS_DATA_PRUNE=true
      - EXECUTIONS_DATA_MAX_AGE=168
      - EXECUTIONS_DATA_PRUNE_MAX_COUNT=10000
      - N8N_DEFAULT_BINARY_DATA_MODE=filesystem
      - NODE_OPTIONS=--max-old-space-size=3072
    volumes:
      - n8n_data:/home/node/.n8n
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - n8n_internal

  caddy:
    image: caddy:2-alpine
    container_name: n8n-caddy
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      - n8n
    networks:
      - n8n_internal

volumes:
  postgres_data:
  n8n_data:
  caddy_data:
  caddy_config:

networks:
  n8n_internal:
    driver: bridge

Launch the stack in detached mode and monitor startup logs:

docker compose up -d
docker compose logs -f n8n

Once the logs display Editor is now accessible via: https://n8n.yourdomain.com/, open your domain in a browser and register your primary owner account.


4. Critical Environment Variables Explained

If you customize this stack for AI agents or high-frequency webhooks (see our n8n AI Integration Architect Guide), keep these environment variables properly tuned:

Variable Recommended Value Why It Matters in Production
WEBHOOK_URL https://n8n.yourdomain.com/ Forces external webhook triggers to generate public HTTPS URLs instead of localhost:5678.
EXECUTIONS_DATA_PRUNE true Automatically purges old execution JSON payloads so PostgreSQL does not fill your NVMe disk.
EXECUTIONS_DATA_MAX_AGE 168 (7 days) Sets retention window in hours. Lower to 48 if running high-frequency cron jobs every minute.
N8N_DEFAULT_BINARY_DATA_MODE filesystem Writes PDFs, images, and audio files to disk instead of holding them in RAM, preventing OOM crashes.
NODE_OPTIONS --max-old-space-size=3072 Allows Node.js to use up to 3 GB on a 4 GB VPS while leaving 1 GB headroom for Postgres, Caddy, and Ubuntu.

5. Automated Daily Backups & Global Error Alerting

A production server requires two automated safety nets: off-site database snapshots and instant failure notifications.

Automated PostgreSQL + Volume Backup Script

Create /usr/local/bin/backup-n8n.sh to export a compressed PostgreSQL dump and archive your .n8n volume daily:

#!/bin/bash
set -e
TIMESTAMP=$(date +%Y%m%d_%H%M)
BACKUP_DIR="/var/backups/n8n/$TIMESTAMP"
mkdir -p "$BACKUP_DIR"

# Load database credentials from /opt/n8n/.env
source /opt/n8n/.env

# 1. Dump PostgreSQL database
docker exec n8n-postgres pg_dump -U "$POSTGRES_USER" "$POSTGRES_DB" | gzip > "$BACKUP_DIR/postgres.sql.gz"

# 2. Archive n8n_data volume
docker run --rm -v n8n_n8n_data:/data -v "$BACKUP_DIR":/backup alpine tar czf /backup/n8n_data.tar.gz -C /data .

# 3. Retain only last 14 days locally (sync to S3/Backblaze B2 via rclone if configured)
find /var/backups/n8n -mindepth 1 -maxdepth 1 -mtime +14 -exec rm -rf {} +

Make it executable and schedule it every night at 03:00 UTC via crontab -e:

sudo chmod +x /usr/local/bin/backup-n8n.sh
(sudo crontab -l 2>/dev/null; echo "0 3 * * * /usr/local/bin/backup-n8n.sh >> /var/log/n8n-backup.log 2>&1") | sudo crontab -

Importable Global Error Handler Workflow (JSON)

Silent failures are the biggest operational blind spot in self-hosted automation. Import this JSON blueprint into a dedicated workflow and assign it as your Error Workflow inside Workflow Settings on all critical pipelines:

{
  "name": "Production Global Error Alert",
  "nodes": [
    {
      "parameters": {},
      "id": "error-trigger-01",
      "name": "Error Trigger",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [240, 300]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "[https://hooks.slack.com/services/REPLACE/WITH/WEBHOOK](https://hooks.slack.com/services/REPLACE/WITH/WEBHOOK)",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "text",
              "value": "=:rotating_light: *n8n Workflow Failed:* {{ $json.workflow.name }}\n*Node:* {{ $json.execution.lastNodeExecuted }}\n*Error:* {{ $json.execution.error.message }}\n*Inspect Run:* {{ $json.execution.url }}"
            }
          ]
        },
        "options": {}
      },
      "id": "slack-alert-02",
      "name": "Dispatch Slack Alert",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [480, 300]
    }
  ],
  "connections": {
    "Error Trigger": {
      "main": [
        [
          {
            "node": "Dispatch Slack Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true
}

6. Post-Deployment Verification Checklist

Before routing live customer webhooks to your new instance, verify these five checks:

  1. TLS & WebSocket Handshake: Open your workflow editor at https://n8n.yourdomain.com/, run a manual test node, and confirm the UI updates instantaneously without hanging on “Executing” (which indicates missing WebSocket upgrade headers).
  2. Webhook URL Resolution: Add a Webhook trigger node and confirm the generated Production URL starts with https://n8n.yourdomain.com/webhook/... rather than http://localhost:5678.
  3. Database Connectivity: Run docker ps and verify n8n-postgres shows (healthy) and n8n-app is bound exclusively to internal ports (5678/tcp without 0.0.0.0:5678).
  4. Hardening & SSH Audit: Confirm password authentication is disabled in /etc/ssh/sshd_config and sudo ufw status lists only ports 22, 80, and 443 (see our n8n Self-Hosting Security Checklist for HMAC webhook verification and Fail2Ban rules).
  5. Routine Maintenance Command: To safely upgrade n8n in the future, run a manual backup first, then execute cd /opt/n8n && docker compose pull && docker compose up -d.

Frequently Asked Questions

What are the minimum VPS requirements to self-host n8n in production?

For reliable production workloads handling 10,000 to 100,000 monthly executions, use a KVM VPS with at least 2 vCPUs, 4 GB of RAM, and 50 GB of NVMe SSD storage (~$6.99 to $12/month). Running n8n on 1 GB RAM instances leads to Node.js Out-of-Memory (OOM) crashes under concurrent webhook loads.

Should I use SQLite or PostgreSQL for self-hosted n8n?

Use PostgreSQL 16 for any production deployment. While n8n defaults to SQLite for zero-config local testing, SQLite locks under concurrent webhook writes and causes execution failures once multiple workflows run simultaneously.

How do I enable HTTPS and SSL for self-hosted n8n?

Never expose port 5678 directly to the public internet. Place Caddy or Nginx in front of the n8n container as a reverse proxy with WebSocket support enabled, and set the WEBHOOK_URL environment variable to your exact https:// subdomain.

How do I back up self-hosted n8n without losing credentials?

A complete n8n backup requires both a daily PostgreSQL database dump (pg_dump) and a backup of your N8N_ENCRYPTION_KEY and /home/node/.n8n volume. Without the exact encryption key, stored API credentials in a restored database cannot be decrypted.

AL

Reviewed & Published by

Andres Lechuga

Web Systems Architect specializing in workflow automation, Docker self-hosting, and API orchestration.