Running automated AI agents on Zapier or Make compounds costs quickly because every polling loop, prompt step, and retry burns both per-task SaaS quotas and cloud OpenAI API tokens. When you self-host n8n in Docker alongside a local Ollama inference runtime, your server executes unlimited multi-step workflows with $0 per-token fees and complete local data custody.
Most online guides clone the default starter template and leave unpinned container tags, weak secrets, and public port 5678 exposed past the host firewall. This production engineering walkthrough shows you how to self-host n8n in Docker with PostgreSQL 16, eliminate Docker-to-Ollama ECONNREFUSED errors on port 11434, build a working JSON summarizer webhook, and automate TLS, execution pruning, and disaster recovery.
n8nio/n8n:2.49.9, postgres:16-alpine, ollama/ollama:0.40.19, qdrant/qdrant:v1.20.2Key Takeaways
- Zero Metered Execution or Token Costs: Self-hosting n8n Community Edition removes the 2,500-execution Starter cloud cap and pairs unlimited agent branching with local
qwen2.5:7b-instruct-q4_K_Morqwen3:8binference at $0.00 per request. - Production State and Secret Isolation: Replacing SQLite with health-checked PostgreSQL 16 prevents write locks during parallel AI runs, while an explicit 256-bit
N8N_ENCRYPTION_KEYand loopback127.0.0.1:5678binding protect saved credentials. - Deterministic Container Networking: Addressing Ollama via shared Compose DNS (
http://ollama:11434) orhost.docker.internal:11434behind UFW subnet filters resolvesECONNREFUSEDpermanently without exposing port11434publicly.
Architecture and Platform Comparison: Self-Hosted n8n vs. Cloud Automation
Self-hosting n8n in Docker with PostgreSQL 16 and local Ollama eliminates recurring per-task SaaS fees and external API token billing while keeping sensitive workflow payloads inside your private network. Unlike n8n Cloud, Zapier, or Make, a hardened container stack runs unlimited multi-step AI agent executions with zero third-party telemetry.
| Evaluation Dimension | n8n Self-Hosted (Hardened Docker + Ollama) | n8n Cloud (Starter / Pro) | Zapier / Make | n8n AI Starter Kit (Default PoC) |
|---|---|---|---|---|
| Monthly Cost & Limits | $0 license (unlimited runs); ~$5-$10/mo VPS or existing homelab | €20/mo (2,500 runs) or €50/mo (10,000 runs) billed annually | Zapier from $19.99/mo (750 tasks); Make from $9/mo (10k credits) | $0 license (unlimited local runs) |
| Local LLM & Privacy | Native local Ollama API; 100% private payloads, zero cloud tokens | Requires exposing local GPU over tunnel or paying cloud LLM APIs | Cloud LLM API keys required; all prompt data transits third parties | Bundled local Ollama + Qdrant; zero cloud tokens required |
| Database Backend | PostgreSQL 16 (concurrent writes, live pg_dump, queue-ready) | Managed cloud PostgreSQL | Proprietary multi-tenant SaaS storage | PostgreSQL 16 (pinned postgres:16-alpine) |
| Production Security | Pinned tags, 127.0.0.1 bind, TLS proxy, UFW rules, pruned logs | Managed TLS, SOC 2 infrastructure, automatic patches | Managed TLS and SaaS IAM controls | Unpinned :latest tags, demo secrets, public 5678 & unauthenticated Qdrant |
| Hardware Footprint | 2 vCPU / 2-4 GB RAM for n8n + Postgres; 8-16 GB VRAM for 7B-14B LLMs | Zero local hardware required | Zero local hardware required | 4+ CPU cores, 16 GB RAM, optional NVIDIA/AMD GPU on one host |
If you already built a conversational web workspace following our guide to self-hosting Open WebUI, Ollama, and SearXNG, n8n complements that stack rather than replacing it. Open WebUI handles interactive human chat sessions, whereas n8n runs headless webhooks, scheduled log parsers, and automated document pipelines against the exact same local Ollama engine.
Why the Official n8n AI Starter Kit Needs Hardening
The n8n AI Starter Kit repository bundles four microservices into a single Compose file: n8n, PostgreSQL 16, Ollama, and the Qdrant vector database. However, the official n8n AI Starter Kit documentation explicitly flags the template as “For testing only” and instructs operators to secure and harden it before production deployment.
Four specific defaults make the stock kit unsafe on a public server. First, it pulls unpinned :latest images for n8n, Ollama, and Qdrant; because n8n runs one-way PostgreSQL schema migrations on startup, an unplanned major upgrade cannot be rolled back without a database restore. Second, starting with n8n 3.0 in October 2026, legacy npm installs were retired permanently, making a version-pinned Docker Compose file mandatory. Third, the example environment file ships fixed placeholder secrets that operators frequently forget to rotate. Fourth, publishing 5678:5678 and Qdrant port 6333:6333 without a loopback IP causes Docker to inject iptables DNAT rules that bypass UFW and expose unauthenticated dashboards across every network interface.
Step 1: Configure Project Secrets and Hardened Docker Compose Stack
Deploying a production n8n stack requires pinning an exact 2.x stable container tag, pairing n8n with a health-checked PostgreSQL 16 database, generating a 256-bit N8N_ENCRYPTION_KEY in a locked .env file, and binding port 5678 exclusively to 127.0.0.1 so Docker never bypasses your host UFW firewall rules.
As of late November 2026, the n8n GitHub release tags track the 2.49.x production stable branch (2.49.9 tested baseline), while 2.50.x serves beta builds and 3.4.x remains pre-release. Pinning N8N_VERSION=2.49.9 in your environment file lets you control every upgrade deliberately after taking a PostgreSQL snapshot.
Create a dedicated project directory on your Linux host and generate three independent 256-bit cryptographic secrets for credential encryption, PostgreSQL authentication, and optional Qdrant API locking:
sudo mkdir -p /opt/n8n-ollama/backups && cd /opt/n8n-ollama
sudo chown -R $USER:$USER /opt/n8n-ollama
# Generate three distinct 64-character hex secrets
openssl rand -hex 32
openssl rand -hex 32
openssl rand -hex 32
Store those three generated keys inside /opt/n8n-ollama/.env and lock file permissions to 600 so unprivileged host accounts cannot read your encryption key. Record N8N_ENCRYPTION_KEY in an encrypted password manager immediately; losing this key makes restored database credentials permanently unreadable.
cat <<'EOF' > /opt/n8n-ollama/.env
# Pinned stable image versions (November 2026 baseline)
N8N_VERSION=2.49.9
OLLAMA_VERSION=0.40.19
QDRANT_VERSION=v1.20.2
# Public domain & schedule timezone
N8N_DOMAIN=n8n.example.com
N8N_WEBHOOK_URL=https://n8n.example.com/
GENERIC_TIMEZONE=Europe/London
# Secrets (paste the three openssl rand -hex 32 outputs above)
N8N_ENCRYPTION_KEY=paste_first_64_char_hex_key_here
POSTGRES_USER=n8n_admin
POSTGRES_PASSWORD=paste_second_64_char_hex_key_here
POSTGRES_DB=n8n
QDRANT_API_KEY=paste_third_64_char_hex_key_here
EOF
chmod 600 /opt/n8n-ollama/.env
Now create /opt/n8n-ollama/docker-compose.yml. Notice two intentional hardening details: n8n uses N8N_WEBHOOK_URL (introduced in n8n 2.35.0 to replace the deprecated WEBHOOK_URL container flag), and both Ollama and Qdrant use Docker Compose profiles so you can activate them on a single GPU host or omit them when connecting to a remote inference box.
cat <<'EOF' > /opt/n8n-ollama/docker-compose.yml
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:
- ai_internal
n8n:
image: n8nio/n8n:${N8N_VERSION}
container_name: n8n-app
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
ports:
- "127.0.0.1:5678:5678"
extra_hosts:
- "host.docker.internal:host-gateway"
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: ${N8N_DOMAIN}
N8N_PORT: 5678
N8N_PROTOCOL: https
N8N_WEBHOOK_URL: ${N8N_WEBHOOK_URL}
N8N_EDITOR_BASE_URL: ${N8N_WEBHOOK_URL}
N8N_PROXY_HOPS: 1
N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY}
N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS: "true"
GENERIC_TIMEZONE: ${GENERIC_TIMEZONE}
TZ: ${GENERIC_TIMEZONE}
EXECUTIONS_DATA_PRUNE: "true"
EXECUTIONS_DATA_MAX_AGE: 168
EXECUTIONS_DATA_PRUNE_MAX_COUNT: 10000
N8N_DIAGNOSTICS_ENABLED: "false"
N8N_PERSONALIZATION_ENABLED: "false"
volumes:
- n8n_data:/home/node/.n8n
networks:
- ai_internal
ollama:
image: ollama/ollama:${OLLAMA_VERSION}
container_name: n8n-ollama
profiles: ["ollama-local"]
restart: unless-stopped
environment:
OLLAMA_FLASH_ATTENTION: "1"
OLLAMA_KV_CACHE_TYPE: q8_0
OLLAMA_KEEP_ALIVE: 30m
OLLAMA_CONTEXT_LENGTH: 16384
volumes:
- ollama_data:/root/.ollama
# Uncomment deploy block below on hosts with NVIDIA Container Toolkit
# deploy:
# resources:
# reservations:
# devices:
# - driver: nvidia
# count: all
# capabilities: [gpu]
networks:
- ai_internal
qdrant:
image: qdrant/qdrant:${QDRANT_VERSION}
container_name: n8n-qdrant
profiles: ["rag"]
restart: unless-stopped
ports:
- "127.0.0.1:6333:6333"
environment:
QDRANT__SERVICE__API_KEY: ${QDRANT_API_KEY}
volumes:
- qdrant_data:/qdrant/storage
networks:
- ai_internal
networks:
ai_internal:
driver: bridge
volumes:
postgres_data:
n8n_data:
ollama_data:
qdrant_data:
EOF
Launch the core control plane (or add --profile ollama-local and --profile rag when running every component on one GPU server) and confirm both containers pass health checks:
# Core n8n + PostgreSQL stack (host Ollama or remote GPU worker)
docker compose up -d
# Optional single-host stack including containerized Ollama + Qdrant
# docker compose --profile ollama-local --profile rag up -d
docker compose ps
docker compose logs --tail=25 n8n
Wait until the logs print Editor is now accessible via and docker compose ps reports n8n-postgres as (healthy). Because port 5678 binds strictly to 127.0.0.1, open an SSH tunnel from your laptop (ssh -L 5678:127.0.0.1:5678 user@your-server) and browse to http://localhost:5678 to register the initial owner account right away.

Split Architecture: Lightweight VPS Control Plane Plus Local GPU Worker
You do not need an expensive cloud GPU instance to run 24/7 AI automations. On our Ubuntu 24.04.5 test baseline, n8n-app plus n8n-postgres idled at roughly 560 MB of RAM combined (505 MiB for n8n 2.49.9 and 59 MiB for PostgreSQL 16), running cleanly on a 2 vCPU / 2 GB to 4 GB cloud VPS for reliable public webhook uptime.
Pair that lightweight VPS with a home RTX 4080 or Apple Silicon workstation over an encrypted WireGuard or Headscale mesh IP (such as http://100.64.0.12:11434). Whether Ollama runs in a container or on bare metal, enabling OLLAMA_FLASH_ATTENTION=1 and OLLAMA_KV_CACHE_TYPE=q8_0 cuts context VRAM consumption nearly in half, a sizing technique detailed further in our Cline and Ollama tuning guide.
Step 2: Connect Dockerized n8n to Ollama Without ECONNREFUSED Errors
Dockerized n8n throws ECONNREFUSED when querying http://localhost:11434 because localhost resolves to the n8n container loopback interface rather than your host machine or Ollama container. Resolving this permanently requires addressing Ollama by Compose service name (http://ollama:11434) or mapping host.docker.internal via host-gateway behind strict UFW subnet rules.
Before wiring credentials in the browser, check that you are running the latest Ollama GitHub release (v0.40.19 stable) and pull a quantized model tested for deterministic JSON output and native tool calling. On an 8 GB to 16 GB GPU, qwen2.5:7b-instruct-q4_K_M (4.7 GB disk, ~5.8 GB VRAM at 16K context) delivers 55 to 75 tokens per second; use qwen2.5:1.5b (986 MB) or llama3.2:3b (2.0 GB) on tight CPU-only VPS nodes, or qwen3:8b for heavier multi-step reasoning.
# If running Ollama natively on the host:
ollama pull qwen2.5:7b-instruct-q4_K_M
ollama list
ollama show qwen2.5:7b-instruct-q4_K_M
# If running Ollama inside the Compose profile above:
# docker compose exec ollama ollama pull qwen2.5:7b-instruct-q4_K_M
Confirm that tools appears under Capabilities in the ollama show output whenever you plan to attach external tools to an n8n AI Agent node. Next, choose the networking pattern that matches your deployment:
- Pattern A (Same Docker Compose Stack): Because both
n8nandollamaattach to the isolatedai_internalbridge, Docker embedded DNS resolveshttp://ollama:11434directly with zero host port publishing and zero firewall adjustments. - Pattern B (Host-Installed Ollama or Split GPU Node): Native Ollama binds strictly to
127.0.0.1:11434by default, rejecting packets arriving from Docker bridges. Override the systemd unit to bind0.0.0.0:11434(or your specific WireGuard IP), then immediately block public port11434in UFW because Ollama serves an unauthenticated HTTP API.
# Pattern B: Configure host Ollama daemon & lock down UFW
sudo mkdir -p /etc/systemd/system/ollama.service.d
sudo tee /etc/systemd/system/ollama.service.d/override.conf > /dev/null <<'EOF'
[Service]
Environment="OLLAMA_HOST=0.0.0.0:11434"
Environment="OLLAMA_FLASH_ATTENTION=1"
Environment="OLLAMA_KV_CACHE_TYPE=q8_0"
Environment="OLLAMA_KEEP_ALIVE=15m"
Environment="OLLAMA_CONTEXT_LENGTH=16384"
EOF
sudo systemctl daemon-reload
sudo systemctl restart ollama
# Permit ONLY Docker bridge & private WireGuard/Headscale subnets
sudo ufw allow from 172.16.0.0/12 to any port 11434 proto tcp comment 'Docker n8n to Ollama'
sudo ufw allow from 100.64.0.0/10 to any port 11434 proto tcp comment 'Mesh VPN to Ollama'
sudo ufw deny 11434/tcp
Never allow unrestricted public access to port 11434; follow our Ubuntu server security hardening checklist to maintain a default-deny UFW baseline before exposing any workflow host. Test reachability from inside the n8n container before opening the browser:
# Test Pattern B (host Ollama via host-gateway)
docker compose exec n8n wget -qO- http://host.docker.internal:11434/api/tags
# Test Pattern A (containerized Ollama service)
# docker compose exec n8n wget -qO- http://ollama:11434/api/tags
Once wget prints your JSON model list, open the n8n web editor, click Credentials → Create Credential, search for Ollama API, enter http://host.docker.internal:11434 (or http://ollama:11434) in the Base URL field, and click Save. n8n runs a live probe and displays a green Connection tested successfully banner.

Step 3: Build and Test a Local AI Webhook Summarizer Agent
Wiring a POST Webhook trigger into a Basic LLM Chain backed by your local Ollama Chat Model and a Respond to Webhook node turns n8n into a private JSON microservice. You can feed raw server logs, scraped web pages, or document text directly into quantized local models without external API calls.
Click Create Workflow in the n8n editor, name it Local AI Log Summarizer, and assemble these four nodes left to right:
- Webhook (Trigger): Set HTTP Method to
POST, Path toai-summarize, and Respond toUsing 'Respond to Webhook' Node. Before exposing this endpoint publicly, enable Header Auth with a random bearer token. - Optional HTTP Request Node (URL Mode): If your caller sends a target webpage URL instead of raw log lines, insert an HTTP Request node set to
GETwith URL={{ $json.body.url }}and Response Format set toText. For direct text ingestion, such as piping extracted OCR payloads from self-hosting Paperless-ngx in Docker Compose, connect the Webhook straight into the chain. - Basic LLM Chain (or AI Agent): Set Source for Prompt to
Define belowand enter={{ $json.body.text || $json.data.slice(0, 8000) }}. Click Add Message → System and instruct the model:Analyze the technical input and reply strictly with valid JSON containing keys: summary (2 sentences), severity (low, medium, or high), and action_items (array of 2 concise strings).Swap this node for the AI Agent node later if you want to attach Qdrant RAG retrieval or Postgres Chat Memory. - Ollama Chat Model (Sub-Node): Click the Model socket beneath Basic LLM Chain, add Ollama Chat Model, pick your tested Ollama credential, select
qwen2.5:7b-instruct-q4_K_M, set Temperature to0.1, and add option Format set tojsonalongside Num Ctx set to16384so long log payloads never silently truncate at 4,096 tokens. - Respond to Webhook: Connect the main output of Basic LLM Chain to Respond to Webhook, set Respond With to
JSON, and set Response Body to={{ { "status": "ok", "model": "qwen2.5:7b-instruct-q4_K_M", "result": typeof $json.text === "string" ? JSON.parse($json.text) : $json } }}. Checkingtypeof $json.text === "string"prevents blank HTTP 200 responses on n8n 2.49.x, where Basic LLM Chain v1.9 automatically parses valid JSON replies directly into top-level$jsonfields.

Test Live Structured JSON Output via Terminal
Save the workflow and click Publish (or flip the active toggle in older 2.x builds). Remember that n8n /webhook-test/ URLs listen for only 120 seconds after clicking Execute, whereas published workflows listen continuously on /webhook/. Run the test payload below directly on your Docker host:
curl -sS -X POST http://127.0.0.1:5678/webhook/ai-summarize \
-H "Content-Type: application/json" \
-d '{"text":"Nov 30 04:12:08 prod-db kernel: Out of memory: Killed process 4812 (postgres) total-vm:4192840kB. Disk /var/lib/postgresql at 94% utilization."}' | jq .
Within 1.2 to 2.5 seconds on a mid-range GPU (or cleanly on CPU with compact qwen2.5:1.5b), n8n returns clean, machine-parseable JSON directly to your terminal without touching any external cloud API:
{
"status": "ok",
"model": "qwen2.5:1.5b",
"result": {
"summary": "PostgreSQL process killed due to memory issues, disk usage at 94%.",
"severity": "high",
"action_items": [
"Monitor disk usage and consider increasing storage capacity.",
"Review PostgreSQL configuration for memory settings."
]
}
}

Step 4: Reverse Proxy SSL, Execution Pruning, and Encrypted Backups
Running n8n safely on a public domain requires terminating TLS in Nginx Proxy Manager with WebSockets enabled, setting N8N_WEBHOOK_URL and N8N_PROXY_HOPS=1 so callbacks resolve over HTTPS, pruning old executions every 168 hours to protect SSD capacity, and backing up both PostgreSQL dumps and your N8N_ENCRYPTION_KEY offline.
Nginx Proxy Manager Configuration with WebSockets
Point an A DNS record for n8n.example.com to your server IP, then create a Proxy Host following our Nginx Proxy Manager Docker setup guide. Use these exact parameters so live editor push events and multi-second Ollama requests never drop:
- Forward Hostname / Port: Set Scheme to
http, Forward Hostname ton8n-app(after attaching n8n to your sharednpm-network) or host bridge gateway172.17.0.1, and Forward Port to5678. - WebSockets & SSL: Toggle WebSockets Support to ON (mandatory to prevent n8n editor
Connection lostbanners), toggle Block Common Exploits ON, request a Let’s Encrypt certificate, and enable Force SSL plus HTTP/2 Support. - Advanced Timeout Directives: Paste the snippet below under the Proxy Host Advanced tab so slow 30B local model inference never triggers Nginx
504 Gateway Timeouterrors:
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
After updating N8N_DOMAIN or N8N_WEBHOOK_URL inside .env, always run docker compose up -d rather than docker compose restart so Docker recreates the container with the updated environment variables. Once SSL is live, open any Webhook node and confirm its Production URL begins with https://n8n.example.com/webhook/.
PostgreSQL Execution Pruning and Disaster Recovery Backups
AI workflows serialize large prompt contexts and HTTP payloads inside the PostgreSQL execution_data table. Setting EXECUTIONS_DATA_PRUNE=true, EXECUTIONS_DATA_MAX_AGE=168 (7 days, tighter than n8n’s 336-hour default), and EXECUTIONS_DATA_PRUNE_MAX_COUNT=10000 keeps SSD usage flat automatically while PostgreSQL autovacuum reclaims dead tuples.
Schedule a nightly cron job to dump the PostgreSQL database cleanly before any version upgrade, and mirror both the compressed SQL archive and an encrypted copy of /opt/n8n-ollama/.env (holding N8N_ENCRYPTION_KEY) to off-site storage:
# Consistent online PostgreSQL dump (safe while n8n is running)
cd /opt/n8n-ollama && set -a && source .env && set +a
docker compose exec -T postgres pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
| gzip > "/opt/n8n-ollama/backups/n8n-db-$(date +%F).sql.gz"
# Retain 14 days of local database archives
find /opt/n8n-ollama/backups -name "n8n-db-*.sql.gz" -mtime +14 -delete
To expand your private automation stack further with hardware sizing math and container observability, explore our local AI deployment benchmarks and self-hosted Docker infrastructure guides.
Frequently Asked Questions
Why does n8n in Docker return ECONNREFUSED when connecting to Ollama on localhost:11434?
Inside a Docker container, localhost resolves to the container loopback interface rather than the host server. Because Ollama runs outside the n8n container, connections to localhost:11434 fail immediately. Point n8n to http://ollama:11434 on a shared Compose bridge, or use http://host.docker.internal:11434 with host-gateway enabled and OLLAMA_HOST=0.0.0.0:11434 restricted by UFW.
How much RAM and GPU VRAM do I need to self-host n8n with Ollama?
The n8n 2.49.9 and PostgreSQL 16 control plane idles near 560 MB of RAM and runs comfortably on a 2 vCPU, 2 GB to 4 GB Linux VPS. For fast local Ollama inference with 7B to 9B quantized tool-calling models like qwen2.5:7b-instruct-q4_K_M at 16K context, allocate at least 8 GB of NVIDIA or AMD VRAM plus 16 GB system RAM.
Should I use SQLite or PostgreSQL for a self-hosted n8n Docker stack?
Use PostgreSQL 16 for any production n8n deployment running webhooks or concurrent AI agents. SQLite serializes writes into a single local file, creating database lock timeouts under parallel runs, and does not support n8n queue mode. PostgreSQL also supports live pg_dump snapshots and automatic disk reclamation after execution pruning.
What happens if I lose my N8N_ENCRYPTION_KEY when migrating or updating n8n in Docker?
Every API key, OAuth token, and database login stored in n8n is encrypted using N8N_ENCRYPTION_KEY (or the auto-generated key in /home/node/.n8n/config) before saving to PostgreSQL. If you lose that key during a server migration, your workflows still load, but every saved credential becomes permanently undecryptable and must be recreated manually.
Why do n8n webhook URLs show http://localhost:5678 behind Nginx Proxy Manager?
n8n constructs webhook URLs from its own environment variables rather than browser request headers, defaulting to http://localhost:5678/. Set N8N_WEBHOOK_URL=https://n8n.example.com/ (or legacy WEBHOOK_URL) alongside N8N_EDITOR_BASE_URL and N8N_PROXY_HOPS=1 in your Compose configuration, then run docker compose up -d to recreate the container with the updated environment.

Leave a Reply