Workflow Automation

n8n PostgreSQL: Setup Guide and Workflow Node Tutorial

J
James Eriksson
··9 min read
Learn how to configure n8n with PostgreSQL, migrate from SQLite, use the Postgres node in workflows, and troubleshoot connection issues. 2026 guide.
TL;DR
  • n8n runs on PostgreSQL by default or SQLite; Postgres is required for production, concurrent workflows, and clustering
  • Configure n8n's backend via eight environment variables (DB_POSTGRESDB_*); Docker Compose example includes both Postgres and n8n services
  • Migrate from SQLite by exporting workflows via CLI, spinning up fresh Postgres, and re-importing; set N8N_ENCRYPTION_KEY to match old instance
  • The Postgres node lets you query external databases inside workflows with SELECT, INSERT, UPDATE, or DELETE operations
  • PostgreSQL handles row-level locking and concurrent requests in parallel; SQLite queues them, reducing throughput 3-5x at scale

n8n can run on PostgreSQL instead of its default SQLite database, and you can also query PostgreSQL databases directly within your workflows using the Postgres node. The first decision is about infrastructure--whether to run n8n's backend on a production-grade database. The second is about data access--whether to connect to external Postgres systems from your automation logic. This guide covers both.

PostgreSQL as n8n's Backend: When and Why

By default, n8n stores its data in SQLite, a lightweight file-based database. This works for testing and hobby projects. SQLite becomes a bottleneck in production when you need concurrent users, reliable backups, clustering, and high uptime. PostgreSQL solves these problems.

SQLite uses table-level locking. When one workflow executes, all others wait. PostgreSQL uses row-level locking and handles concurrent requests efficiently. If you run five workflows simultaneously on SQLite, they queue behind one another. On PostgreSQL, they execute in parallel.

Backup and disaster recovery differ too. SQLite backups are file copies--simple but risky if your server crashes mid-backup. PostgreSQL offers point-in-time recovery, streaming replication, and standard backup tools. For a 10-person team running n8n as a core service, PostgreSQL is not optional.

Queue mode (n8n's distributed worker architecture) requires PostgreSQL. If you deploy multiple n8n instances behind a load balancer, they must share a database. SQLite cannot do this. PostgreSQL can.

Scaling checklist: Does your team run more than three workflows per hour? Do you have more than three n8n users? Do your workflows consume more than 100 MB of execution history? If you answered yes to any of these, migrate to PostgreSQL.

How to Configure n8n to Use PostgreSQL

Configuring n8n for PostgreSQL takes three steps: set up a Postgres database and user, pass connection details to n8n via environment variables, and verify the connection.

First, create a PostgreSQL database and dedicated user. If Postgres is running locally, connect using psql and run these commands:

CREATE DATABASE n8n_db;
CREATE USER n8n_user WITH PASSWORD 'your-secure-password-here';
ALTER ROLE n8n_user WITH CREATEDB;
GRANT ALL PRIVILEGES ON DATABASE n8n_db TO n8n_user;

Note the database name, username, password, and host. You will pass these to n8n as environment variables.

Next, configure n8n to connect. Set these eight environment variables:

  • DB_TYPE=postgresdb
  • DB_POSTGRESDB_HOST=your-postgres-host (e.g., localhost or 1.2.3.4)
  • DB_POSTGRESDB_PORT=5432 (default Postgres port)
  • DB_POSTGRESDB_DATABASE=n8n_db
  • DB_POSTGRESDB_USER=n8n_user
  • DB_POSTGRESDB_PASSWORD=your-secure-password-here
  • DB_POSTGRESDB_SCHEMA=public (default; use a custom schema if you prefer)
  • DB_POSTGRESDB_SSL_ENABLED=false (set to true if your database uses SSL/TLS)

For Docker deployments, create a docker-compose.yml file that runs both PostgreSQL and n8n, with shared networking:

version: '3'
services:
  postgres:
    image: postgres:18-alpine
    environment:
      POSTGRES_DB: n8n_db
      POSTGRES_USER: n8n_user
      POSTGRES_PASSWORD: your-secure-password-here
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U n8n_user -d n8n_db"]
      interval: 10s
      timeout: 5s
      retries: 5

  n8n:
    image: n8n:latest
    environment:
      DB_TYPE: postgresdb
      DB_POSTGRESDB_HOST: postgres
      DB_POSTGRESDB_PORT: 5432
      DB_POSTGRESDB_DATABASE: n8n_db
      DB_POSTGRESDB_USER: n8n_user
      DB_POSTGRESDB_PASSWORD: your-secure-password-here
      N8N_HOST: 0.0.0.0
      N8N_PORT: 5678
    ports:
      - "5678:5678"
    depends_on:
      postgres:
        condition: service_healthy
    volumes:
      - n8n_data:/home/node/.n8n

volumes:
  postgres_data:
  n8n_data:

Run docker-compose up and wait for n8n to initialize the schema. The first startup takes longer--n8n creates tables and indices in Postgres. This is normal.

To verify the connection, check n8n's logs: docker-compose logs n8n | grep -i postgres. You should see "Database connection successful" or similar. If you see "connection refused," check that Postgres is running and the hostname is correct.

Access n8n at localhost:5678 in your browser, create your first credential, and save it. If the credential saves without errors, Postgres is working.

Migrating from SQLite to PostgreSQL

If you already run n8n on SQLite, migration is possible but requires care. You export your workflows and credentials, then point n8n at the new Postgres database.

Step one: Back up your SQLite database. In your n8n directory, copy the .n8n folder and all files inside it. This is your insurance policy.

Step two: Export workflows and credentials using the n8n CLI. If n8n is running in Docker, run commands like this:

docker exec <n8n-container-id> n8n export:workflow --output=/home/node/.n8n/exported_workflows.json
docker exec <n8n-container-id> n8n export:credentials --output=/home/node/.n8n/exported_credentials.json

This creates JSON files you can transfer to a new n8n instance.

Step three: Spin up a fresh n8n instance with the Docker Compose config above. Do not reuse your old SQLite database.

Step four: Import your workflows and credentials:

docker exec <new-container-id> n8n import:workflow --input=/home/node/.n8n/exported_workflows.json
docker exec <new-container-id> n8n import:credentials --input=/home/node/.n8n/exported_credentials.json

Common migration gotchas: Encrypted credentials may not transfer if the encryption key differs between instances. Set N8N_ENCRYPTION_KEY to the same value on both instances. API tokens and webhook URLs are instance-specific--update them after import. Some third-party integrations may require re-authentication.

Using the Postgres Node in Workflows

The Postgres node lets you query and modify external PostgreSQL databases from within n8n workflows. This is separate from configuring n8n's own database.

To use the Postgres node, you first create a Postgres credential in n8n. Click "Credentials" > "Create New" > "Postgres Database". Enter the connection details for the target database (the one you want to query, not n8n's backend database). Include the host, port, database name, username, and password.

Once saved, drag a Postgres node into your workflow. Click the node and select your credential from the dropdown.

The node supports four operation types: "Execute Query" (run any SQL), "Insert" (add rows), "Update" (modify rows), and "Delete" (remove rows).

Simple SELECT example: Retrieve customer names and emails from a table.

Set Operation to "Execute Query" and paste:

SELECT name, email FROM customers WHERE created_at > NOW() - INTERVAL '7 days';

When the workflow runs, the Postgres node executes this query and passes the results to the next node. Use these results to send emails, update a CRM, or trigger other actions.

Multi-row insert example: Add new customers from an external API.

If a previous node fetches customer data from an API, the Postgres node can insert it. Set Operation to "Insert", specify the table ("customers"), and map the API fields to column names. The node will insert one row per input item. If the API returns three customers, it inserts three rows.

Transactions and error handling: For complex workflows, use "Execute Query" with explicit transactions:

BEGIN;
UPDATE accounts SET balance = balance - $1 WHERE id = $2;
UPDATE accounts SET balance = balance + $1 WHERE id = $3;
COMMIT;

If either UPDATE fails, the entire transaction rolls back. This prevents money transfers from completing halfway.

Advanced: PostgreSQL 16+ supports vector data types via pgvector. The Postgres node can store and query embeddings (1,000-dimensional vectors from AI models). This enables semantic search and recommendation workflows. See the n8n documentation for pgvector examples.

Performance and Scaling: Postgres vs SQLite

PostgreSQL outperforms SQLite at scale in four measurable ways:

Concurrency: SQLite locks the entire table during writes. Five simultaneous workflows see serial execution. PostgreSQL locks individual rows and handles five concurrent requests in parallel, reducing total execution time 3-5x.

Execution history: n8n stores every workflow run, input, and output for audit trails and debugging. With SQLite, queries against 100,000+ runs slow down noticeably. PostgreSQL indices make these queries instant.

Distributed deployment: Queue mode runs multiple n8n instances, each processing workflows independently. They pull jobs from a shared database. Only PostgreSQL scales this way. SQLite would deadlock.

Backup and failover: PostgreSQL streaming replication syncs data to a hot standby. If the primary server crashes, failover is automatic. SQLite backups are file copies--failover is manual and risky.

When is SQLite still acceptable? For solo projects, development environments, testing, and teams with fewer than three concurrent users and under 10 workflows. If your workload is predictable and small, SQLite works fine and reduces infrastructure complexity.

Troubleshooting Common Issues

"Connection refused" error: PostgreSQL is not running or the host/port are wrong. Check that Postgres is listening on 5432 and your firewall allows traffic. Verify the hostname: "localhost" works from the same container; use the service name ("postgres") in Docker Compose.

"Permission denied for schema public": The database user lacks privileges. Run GRANT ALL PRIVILEGES ON SCHEMA public TO n8n_user; as the Postgres superuser (usually "postgres").

"SSL certificate problem": If you set DB_POSTGRESDB_SSL_ENABLED=true but Postgres is not configured for SSL, disable it or install a certificate. For testing, disable SSL first, then enable it once n8n connects.

Workflows lose data after migration: You exported workflows but re-authenticated integrations are missing. Credentials do not always transfer cleanly between instances. Re-enter API keys and passwords manually in the new instance.

Slow query in Postgres node: Add an index on the column you filter by. Example: CREATE INDEX idx_customers_email ON customers(email);. Check n8n logs for the actual query and test it directly in Postgres to find bottlenecks.

Data inconsistency: If you query the same table twice and get different results, verify that multiple n8n instances are not writing concurrently. Use explicit transactions (BEGIN/COMMIT) to prevent race conditions.

For deeper troubleshooting, check n8n logs at /home/node/.n8n/logs inside the container or in stdout if running foreground. Look for database connection messages and SQL errors.

Frequently Asked Questions

Can I switch back to SQLite after using Postgres? Technically yes, but practically no. The Postgres schema is richer than SQLite's. To downgrade, export all data from Postgres and re-initialize SQLite, losing execution history. Not recommended.

What PostgreSQL version does n8n support? n8n officially supports PostgreSQL 16, 17, and 18 as of 2026. Version 15 and earlier may work but are not tested. Use a supported version for production.

Can the Postgres node connect to managed services like Amazon RDS or Heroku Postgres? Yes. Use the connection string provided by your hosting provider. If the host is my-db.c123.us-east-1.rds.amazonaws.com, enter that in the Postgres node credential. Enable SSL if required by the provider.

Will migrating to Postgres improve workflow speed? It improves throughput (how many workflows run simultaneously), not latency (how fast one workflow executes). If your workflows are I/O bound (waiting for external APIs), Postgres speeds them up by reducing database lock contention. CPU-bound workflows show minimal speedup.

How large can the execution history grow? Without cleanup, n8n's execution history grows indefinitely. With SQLite, the file expands until disk space runs out. PostgreSQL does not care about file size, but queries slow down after several million rows. Implement retention policies: DELETE FROM execution_entity WHERE finished_at < NOW() - INTERVAL '90 days'; monthly.

Is there a simple way to verify Postgres connectivity from Docker? Yes. Run docker exec <postgres-container> psql -U n8n_user -d n8n_db -c "SELECT 1;". If you see "1" in the output, Postgres is alive and your credentials are correct.

Can I run n8n and PostgreSQL on separate servers? Yes. Set DB_POSTGRESDB_HOST to the IP or hostname of the Postgres server (not "localhost"). Ensure n8n's server can reach Postgres on port 5432. Use SSL and strong passwords if the servers communicate over the internet.

The Bottom Line

PostgreSQL is the right database for any n8n deployment that runs more than a handful of workflows or serves a team. The setup takes 15 minutes with Docker Compose. The benefits--concurrency, backups, scalability--are immediate and compound as your automation grows.

If you are building n8n workflows today and do not want to worry about database infrastructure later, Opsily's managed n8n hosting includes PostgreSQL, automated backups, and clustering out of the box. Get started free at https://console.opsily.com.

Skip the database work
Opsily handles Postgres, backups, and scaling for n8n so you focus on workflows.
Get Started Free

Ready to self-host your own apps?

One server. Multiple apps. No per-app fees.

Get started →