n8n Self-Hosting Guide: Automate Your AI Workflows for Free

Proprietary automation platforms like Zapier and Make have become indispensable for connecting SaaS services. However, their consumption-based pricing models punish companies that process high volumes of data. When you introduce AI workflows—evaluating customer tickets, scraping competitor feeds, or querying vector stores—a single multi-step automation can consume dozens of tasks per execution, driving monthly SaaS bills into thousands of dollars.

n8n is an open-source workflow automation platform that solves this cost barrier. Featuring fair-code licensing, a visual canvas, and native Advanced AI Agent nodes, self-hosted n8n gives you unlimited workflow executions, zero per-task billing, and complete control over customer data. In this comprehensive DevOps tutorial, we build a production-hardened n8n deployment with PostgreSQL, Docker Compose, and automated SSL termination.

Why Self-Host n8n Instead of Cloud Automation?

Self-hosting n8n offers three major engineering advantages:

  • $0 Task Fees: Run millions of workflow executions without paying a penny in platform overage charges; you pay only for underlying VPS hardware.
  • Data Privacy & Compliance: Credentials, customer PII, and internal database records remain within your private VPC, satisfying GDPR and HIPAA requirements.
  • Native LangChain AI Nodes: Connect Claude 3.5 Sonnet, OpenAI, or local Ollama instances directly to your workflows using visual agents, memory buffers, and tool calling.

For ideas on connecting internal databases to your workflows, check out our guide on connecting PostgreSQL with Claude via MCP.

Production Architecture: Docker Compose with PostgreSQL

While n8n can run using an embedded SQLite database for testing, production workloads with concurrent webhook triggers require PostgreSQL to prevent database locks. Here is a production-ready docker-compose.yml file:

version: '3.8'

services:
  postgres:
    image: postgres:16-alpine
    container_name: n8n_postgres
    restart: unless-stopped
    environment:
      - POSTGRES_USER=n8n_admin
      - POSTGRES_PASSWORD=SuperSecretDbPassword2026!
      - POSTGRES_DB=n8n_production
    volumes:
      - ./postgres_storage:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U n8n_admin -d n8n_production"]
      interval: 10s
      timeout: 5s
      retries: 5

  n8n:
    image: docker.n8n.io/n8nio/n8n:latest
    container_name: n8n_app
    restart: unless-stopped
    ports:
      - "5678:5678"
    environment:
      - N8N_HOST=n8n.yourdomain.com
      - N8N_PORT=5678
      - N8N_PROTOCOL=https
      - NODE_ENV=production
      - WEBHOOK_URL=https://n8n.yourdomain.com/
      - GENERIC_TIMEZONE=UTC
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=postgres
      - DB_POSTGRESDB_PORT=5432
      - DB_POSTGRESDB_DATABASE=n8n_production
      - DB_POSTGRESDB_USER=n8n_admin
      - DB_POSTGRESDB_PASSWORD=SuperSecretDbPassword2026!
      - N8N_ENCRYPTION_KEY=94e72a819b0d4c82b9a71e8473
      - EXECUTIONS_DATA_PRUNE=true
      - EXECUTIONS_DATA_MAX_AGE=168
    volumes:
      - ./n8n_storage:/home/node/.n8n
    depends_on:
      postgres:
        condition: service_healthy

Critical Environment Configurations Explained

  • N8N_ENCRYPTION_KEY: A 32-character random string used to encrypt all OAuth credentials and API keys stored in PostgreSQL. Store this key securely in a password manager. If lost, stored credentials cannot be recovered.
  • EXECUTIONS_DATA_PRUNE=true: Automatically purges historical execution logs older than 168 hours (7 days). Without this setting, execution logs can quickly consume gigabytes of disk space.
  • WEBHOOK_URL: Must match your public HTTPS domain so that external services (Stripe, GitHub, Slack) can deliver webhook payloads successfully.

Step 2: Reverse Proxy and SSL Termination with Caddy

To serve n8n securely over HTTPS without configuring complex Certbot renewals, place Caddy in front of port 5678. Here is a minimal Caddyfile:

n8n.yourdomain.com {
    reverse_proxy localhost:5678 {
        flush_interval -1
    }
}

Caddy automatically provisions Let's Encrypt TLS certificates, routes traffic, and handles HTTP/2 and WebSocket connections required for n8n's real-time canvas updates.

Building Your First AI Agent Workflow in n8n

Once deployed, log into your n8n dashboard and create a new workflow:

  1. Webhook Trigger: Configure an incoming HTTP POST endpoint to receive bug reports from your frontend error tracker.
  2. AI Agent Node: Drag an AI Agent node onto the canvas. Set its mode to Tools Agent.
  3. Model Connector: Attach an Anthropic Chat Model sub-node configured with Claude 3.5 Sonnet.
  4. Tool Node: Attach a GitHub Tool node with permissions to search repository issues and create issue tickets.
  5. Execution: When an incoming error arrives, the AI agent searches GitHub to determine if a duplicate issue exists. If found, it appends a comment; if new, it creates a formatted bug report with reproduction steps.

Scaling n8n with Redis Queue Mode for High Concurrency

When webhook volume exceeds 20 requests per second, a single n8n instance can experience thread blocking. To scale horizontally, switch n8n from default mode to Redis Queue mode:

  • Primary / Leader Container: Handles the web UI, workflow saving, and webhook ingestion. Dispatches incoming execution jobs to Redis.
  • Worker Containers: Headless n8n containers (n8n worker) that pull jobs from Redis, execute LLM node logic, and write results back to PostgreSQL.
  • Redis Broker: A dedicated Redis container managing job queues and execution states with zero message loss.
# Environment variables for n8n worker containers
EXECUTIONS_MODE=queue
QUEUE_BULL_REDIS_HOST=redis
QUEUE_BULL_REDIS_PORT=6379
DB_TYPE=postgresdb
DB_POSTGRESDB_HOST=postgres

Monitoring Performance: Prometheus Metrics and Healthchecks

In enterprise production environments, operations engineers need real-time visibility into workflow execution throughput, failure spikes, and queue latency. You can enable native Prometheus metrics inside n8n by configuring two environment variables:

N8N_METRICS=true
N8N_METRICS_PREFIX=n8n_

This exposes an internal /metrics endpoint compatible with Prometheus scrapers, allowing you to build Grafana alerting dashboards for active worker counts, queue depths, and execution runtimes.

Automated Disaster Recovery: Daily Database Dumps to S3

A reliable self-hosting deployment must feature automated off-site backups. You can write a lightweight bash script executed via cron that dumps the PostgreSQL database and syncs the encryption key to an AWS S3 bucket or Cloudflare R2:

#!/bin/bash
# /opt/scripts/backup_n8n.sh: Daily S3 backup
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="/tmp/n8n_backup_$TIMESTAMP"
mkdir -p "$BACKUP_DIR"

# 1. Dump PostgreSQL schema and data
docker exec -t n8n_postgres pg_dump -U n8n_admin n8n_production | gzip > "$BACKUP_DIR/db_$TIMESTAMP.sql.gz"

# 2. Archive encryption keys and custom credentials
tar -czf "$BACKUP_DIR/n8n_config_$TIMESTAMP.tar.gz" -C /Volumes/Data/n8n_storage .

# 3. Encrypt and upload to Cloudflare R2 / AWS S3
aws s3 sync "$BACKUP_DIR" s3://my-enterprise-backups/n8n/

# 4. Clean local temporary files
rm -rf "$BACKUP_DIR"
echo "n8n backup completed and uploaded to S3 successfully."

To optimize cloud storage expenses, configure an S3 bucket lifecycle rule that transitions dumps older than 30 days to AWS Glacier or deletes archives older than 90 days. Always schedule a recurring monthly restore drill in an isolated staging environment to verify that backup tarballs and PostgreSQL dumps restore cleanly without schema corruption.

For more architectural insights on multi-agent execution, check our comparison of LangGraph vs CrewAI.

Cost Comparison: Self-Hosted n8n vs Cloud Zapier

Here is an empirical cost comparison for a high-volume SaaS processing 150,000 tasks per month:

Expense Item Zapier Professional Plan Self-Hosted n8n (Hetzner VPS)
Monthly Platform Cost $1,199.00 / month $0.00 (Fair-code license)
Compute / Server Cost Included $14.50 / month (4 vCPU, 8GB RAM)
Execution Quota Limit Capped at 150k tasks Unlimited executions
Annual Total Cost $14,388.00 / year $174.00 / year

To learn more about our data management and security policies, review our Privacy Policy.

Frequently Asked Questions (FAQ)

Is self-hosted n8n free for commercial enterprise use?

Yes, for internal business automation. Under the Sustainable Use License, you can self-host n8n and use it to run internal company workflows completely free. You only require an enterprise license if you offer n8n as a paid white-label managed service to third-party clients.

How do I backup my self-hosted n8n instance?

Create automated nightly cron backups of two items: 1) the PostgreSQL database dump using pg_dump, and 2) the ./n8n_storage directory containing community nodes and encryption key state. With both artifacts, a complete restore takes under 5 minutes.

Can self-hosted n8n connect to local AI models running on Ollama?

Yes. Add an Ollama Chat Model node to your canvas and set the base URL to http://host.docker.internal:11434 (or the private IP of your GPU server). You can invoke models like Llama 3.3 or Qwen 2.5 with zero external API fees.

What hardware specifications are recommended for 50,000 daily executions?

For high concurrency, a standard VPS with 4 dedicated vCPUs, 8GB of RAM, and fast NVMe storage running Ubuntu 24.04 handles up to 50 concurrent workflow threads smoothly. For higher loads, n8n supports scaling via Redis queue mode with multiple worker containers.