Home Server › Containers

Self-hosting n8n with PostgreSQL and Docker Compose

Self-host n8n on a homelab with Docker Compose and PostgreSQL 16, configure WebSocket proxying in Nginx Proxy Manager, and build event-driven alert pipelines.

Self-hosting n8n with PostgreSQL and Docker Compose

Hosted automation platforms like Zapier and Make hit task-run limits quickly and route internal credentials through third-party servers. Here is how I self-host n8n with Docker Compose and PostgreSQL 16, expose it over WebSockets via Nginx Proxy Manager, and wire up webhook-driven server alerts.

Tested with Docker Compose v2, PostgreSQL 16 (postgres:16-alpine), n8n (docker.n8n.io/n8nio/n8n:latest), and Nginx Proxy Manager.


Why self-host workflow automation

Once a homelab or side-project stack grows past a handful of containers, glue work piles up fast:

  • Sending a Telegram or Slack alert when a healthcheck fails or a container crashes
  • Receiving a GitHub webhook, parsing release notes, and logging them in a Notion database
  • Aggregating nightly backup logs into a single daily summary email

Zapier and Make are usually the first tools people reach for, but hosted SaaS automation runs into three hard limits in a self-hosted environment:

  1. Tight task-run quotas on free and entry tiers: Polling an endpoint every minute or processing bursty webhooks burns through monthly task caps in days.
  2. External credential exposure: Internal API tokens, webhook secrets, and private payloads have to leave your network and pass through a third-party cloud.
  3. Restricted custom code execution: Running arbitrary JavaScript (Node.js) or Python with custom logic is either locked behind expensive tiers or heavily sandboxed.

n8n is a fair-code workflow automation engine with over 400 built-in integrations. Self-hosting it removes execution limits and keeps every API token and payload inside your own network.

CriterionHosted SaaS (Zapier / Make)Self-hosted n8n (Docker + PostgreSQL)
Execution limitsMetered per task or operationUnlimited (bounded only by host CPU/RAM)
Data residencyThird-party cloud serversLocal homelab / private VPC
Custom codeLimited or paid add-onNative Code node (JS/Python)
Maintenance overheadZeroImage updates, DB backups, reverse proxy

When not to use n8n: If you need ultra-low-latency, high-throughput event streaming (thousands of events per second) or strict version-controlled business logic tested in CI, write a dedicated service or worker instead. n8n shines for glue workflows, webhooks, and operational automation—not as a replacement for a core backend.


Architecture and network flow

By default, n8n stores workflows and execution history in a local SQLite file. That works for quick local trials, but concurrent webhook bursts quickly trigger SQLite write-lock contention and make backups awkward. For a reliable homelab deployment, I back n8n with a dedicated PostgreSQL 16 container.

In front of n8n, Nginx Proxy Manager (NPM) terminates TLS and forwards both standard HTTPS webhook traffic and persistent WebSocket connections used by the n8n editor UI to stream live node execution states.

flowchart TD
    subgraph External["External Clients and Services"]
        User["Browser (n8n Editor UI)"]
        GitHub["GitHub / External Webhooks"]
        Telegram["Telegram / Slack Bot API"]
    end

    subgraph Proxy["Reverse Proxy Layer"]
        NPM["Nginx Proxy Manager<br/>(TLS + WebSocket Proxy)"]
    end

    subgraph DockerNet["Docker Bridge (homelab-network)"]
        N8N["n8n Engine<br/>(Port 5678)"]
        PG["PostgreSQL 16<br/>(Port 5432, internal)"]
        VolN8N[("n8n_data<br/>(Config & Encryption Key)")]
        VolPG[("postgres_data<br/>(Execution History & State)")]
        N8N --> VolN8N
        PG --> VolPG
        N8N -->|"SQL Connection"| PG
    end

    User -->|"HTTPS :443 + WSS"| NPM
    GitHub -->|"POST /webhook/*"| NPM
    NPM -->|"http://n8n-app:5678"| N8N
    N8N -->|"Outbound Bot API"| Telegram

Notice that PostgreSQL never publishes port 5432 to the host. Only containers attached to homelab-network can resolve and reach it.


Docker Compose and environment setup

Start by laying out a clean project directory so configuration and bind-mounted data stay easy to back up:

1
2
3
4
5
6
n8n/
├── docker-compose.yml
├── .env
└── data/
    ├── n8n/
    └── postgres/

Environment variables (.env)

Keep database passwords, the public hostname, and the credential encryption key out of docker-compose.yml by storing them in .env:

# .env
# PostgreSQL settings
POSTGRES_USER=n8n_admin
POSTGRES_PASSWORD=n8n_secure_db_password_xxxx
POSTGRES_DB=n8n

# n8n public domain and webhook settings
DOMAIN_NAME=n8n.example.com
SUBDOMAIN=n8n
GENERIC_TIMEZONE=Asia/Seoul
N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true
N8N_ENCRYPTION_KEY=your_generated_random_32char_key_xxxx

N8N_ENCRYPTION_KEY encrypts every credential (API keys, OAuth tokens, bot secrets) stored in n8n’s database. If you change or lose this key later, n8n cannot decrypt existing credentials. Generate a random 32-character value once and store a copy in your password manager.

Docker Compose specification (docker-compose.yml)

Use depends_on with condition: service_healthy so n8n waits until PostgreSQL actually accepts connections before running database migrations (I covered this readiness pattern in ordering Compose startup with depends_on and healthchecks).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 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:
      - ./data/postgres:/var/lib/postgresql/data
    networks:
      - homelab-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -h localhost -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 5s
      timeout: 5s
      retries: 10

  n8n:
    image: docker.n8n.io/n8nio/n8n:latest
    container_name: n8n-app
    restart: unless-stopped
    ports:
      - "5678: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}
      - N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=${N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS}
      - N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}
      - EXECUTIONS_DATA_PRUNE=true
      - EXECUTIONS_DATA_MAX_AGE=168 # Auto-delete execution logs older than 7 days
    volumes:
      - ./data/n8n:/home/node/.n8n
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - homelab-network

networks:
  homelab-network:
    name: homelab-network
    driver: bridge

Start the stack with docker compose up -d and verify both containers report healthy or Up via docker compose ps.


Reverse proxy and WebSocket setup

When you test a workflow on the n8n canvas, the backend pushes live node status updates and execution logs to your browser over a WebSocket connection. If your reverse proxy only forwards plain HTTP, the editor UI disconnects or freezes during test runs.

In Nginx Proxy Manager, create a Proxy Host with these settings (see my Cloudflare DDNS and NPM wildcard SSL setup if you still need TLS certificates):

  1. Domain Names: n8n.example.com
  2. Forward Hostname / IP: n8n-app (when NPM shares homelab-network) or your host LAN IP
  3. Forward Port: 5678
  4. Cache Assets: OFF
  5. Block Common Exploits: ON
  6. Websockets Support: ON (required)

Enabling Websockets Support injects the standard HTTP/1.1 upgrade headers into the Nginx location block:

1
2
3
4
5
# Nginx directives injected when Websockets Support is enabled
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;

If WEBHOOK_URL is missing or does not match your public HTTPS domain, n8n generates webhook endpoints pointing to http://localhost:5678. External callers like GitHub or Slack will fail with Connection Refused until WEBHOOK_URL matches the reverse proxy URL.


Building a server alert pipeline

After opening https://n8n.example.com and creating the owner account, I build a practical operational pipeline: accept failure webhooks from my monitoring stack, fire an immediate Telegram alert only when a service is down, and archive every event in Notion.

flowchart TD
    Hook["Webhook Node<br/>(POST /webhook/server-alert)"] --> Check{"IF Node<br/>(status == 'DOWN')"}
    Check -->|"True (Incident)"| Tele["Telegram Node<br/>(Send On-Call Alert)"]
    Check -->|"False (Recovered)"| Notion["Notion Node<br/>(Append Audit Log)"]
    Tele --> Notion

Node-by-node setup

  1. Webhook node:
    • HTTP Method: POST
    • Path: server-alert
    • Response Mode: On Received (returns 200 OK immediately so the caller never times out)
    • Sample incoming JSON payload:
      1
      2
      3
      4
      5
      6
      
      {
        "service": "api-gateway",
        "status": "DOWN",
        "timestamp": "2026-10-30T10:15:00Z",
        "error_message": "Connection timed out (504)"
      }
      
  2. IF node (branching):
    • Condition: {{ $json.body.status }} equals DOWN
    • Routing only active outages to Telegram cuts alert fatigue while still recording recovery events.
  3. Telegram node (instant alert):
    • Operation: Send Text Message
    • Chat ID: ${TELEGRAM_CHAT_ID}
    • Markdown message body:

      1
      2
      3
      4
      5
      
      [Homelab Incident Detected]
      - Service: {{ $json.body.service }}
      - Status: {{ $json.body.status }}
      - Time: {{ $json.body.timestamp }}
      - Error: {{ $json.body.error_message }}
      
  4. Notion node (audit archive):
    • Regardless of whether the event is an outage or recovery, create a new page in an “Infrastructure Incident Log” database so you keep a searchable timeline.

AI workflow building and MCP integration

Historically, building complex n8n flows meant dragging dozens of nodes onto the canvas and hand-wiring nested JSON expressions ($json.body...). Modern n8n releases add two capabilities that change how fast you can assemble workflows:

  1. Natural-language workflow drafting: Instead of wiring every boilerplate IF branch and parser node by hand, you can describe the trigger, transformation, and destination (“receive a GitHub release webhook, parse the Markdown body, log it to Notion, and notify Telegram”) and refine the generated graph.
  2. MCP (Model Context Protocol) server and client support:
    • Coding agents calling n8n: Exposing n8n workflows through an MCP server lets desktop clients or coding agents discover your existing GitHub, Slack, database, and Google Sheets automations as callable tools.
    • n8n calling external MCP tools: Inside n8n’s AI Agent node, you can attach external MCP servers (local filesystem search, browser automation, SQL queries) so a workflow can run multi-step autonomous tasks.
flowchart TD
    Prompt["Natural-Language Prompt<br/>('Log new release to Notion and alert Slack')"] --> Agent["AI Coding Agent<br/>(Claude / Cursor / IDE)"]
    Agent -->|"MCP Tool Call"| N8N_MCP["n8n MCP Server API"]
    N8N_MCP -->|"Generate & Trigger Flow"| Flow["n8n Workflow Pipeline"]
    Flow -->|"Execute Integrations"| Services["GitHub / Notion / Telegram"]

You still need to review credentials, error branches, and rate limits, but delegating the repetitive node wiring lets you focus on the actual event contract and failure handling.


Execution pruning, upgrades, and caveats

When workflows run hundreds or thousands of times a day, execution payloads inflate PostgreSQL storage quickly. Keep automatic pruning enabled in docker-compose.yml so old runs are cleaned up nightly:

1
2
3
- EXECUTIONS_DATA_PRUNE=true
- EXECUTIONS_DATA_MAX_AGE=168 # Retain 7 days of execution history
- EXECUTIONS_DATA_PRUNE_MAX_COUNT=10000

When upgrading n8n manually, pull the updated image and recreate the container without touching the bind-mounted volumes:

1
2
3
# Pull the latest n8n image and recreate the container
docker compose pull
docker compose up -d --remove-orphans

Production caveats and checklist

  • Pin versions before major upgrades: Using :latest is convenient in a lab, but back up ./data/postgres before pulling a major n8n release in case a database migration cannot be rolled back.
  • Lock down webhook endpoints: Public /webhook/* URLs accept unauthenticated POST requests by default. Enable Header Auth or HMAC signature verification on any webhook exposed through NPM.
  • Pre-launch checklist:
    • N8N_ENCRYPTION_KEY backed up outside the server
    • WEBHOOK_URL matches the public HTTPS domain in Nginx Proxy Manager
    • Websockets Support enabled on the NPM proxy host
    • EXECUTIONS_DATA_PRUNE=true and EXECUTIONS_DATA_MAX_AGE configured
    • PostgreSQL port 5432 stays internal to homelab-network

Once n8n is ready to receive webhooks, the natural next piece is a lightweight service monitor that detects outages and fires those webhooks in the first place—I documented my setup in homelab uptime monitoring and status pages with Uptime Kuma.

This post is licensed under CC BY 4.0 by the author.