node cookbook

n8n Postgres Node: Query Safely and Debug Production Failures

Use the Postgres node when a workflow needs to query, insert, update, or transform data in PostgreSQL, but first prove credentials, network access, SSL, permissions, and result size are safe for production.

Match your incident first

Start with the symptom you can prove

Jump to checks

getaddrinfo ENOTFOUND localhost or connect ECONNREFUSED 127.0.0.1:5432

First check: Check the credential host field and confirm whether Postgres is a Compose service, managed database, or external host.

Wrong fix to avoid: Do not expose Postgres publicly just to make localhost work.

Verify: A tiny SELECT 1 query succeeds from the same n8n instance or worker that runs the workflow.

password authentication failed for user

First check: Confirm the Postgres node credential name, database user, target database, and whether the password was recently rotated.

Wrong fix to avoid: Do not switch to a superuser credential to make the error disappear.

Verify: The workflow credential connects with a least-privilege user and the intended query succeeds.

permission denied for table, schema, or sequence

First check: Run a minimal query against the exact table and operation the workflow needs, not only SELECT 1.

Wrong fix to avoid: Do not grant broad admin permissions before identifying the specific missing privilege.

Verify: The same user can read or write only the intended schema/table and cannot access unrelated tables.

Use when
n8n workflows, Postgres
First check
Separate whether n8n itself cannot start or only a workflow Postgres node cannot connect.
Time to check
5-10 minutes
Next step
Match the symptom, then run the verification checks.

Independent third-party notes. n8n is a trademark of its owner and is referenced only for compatibility and troubleshooting context.

Quick Answer

Use the Postgres node when a workflow needs to query, insert, update, or transform data in PostgreSQL, but first prove credentials, network access, SSL, permissions, and result size are safe for production.

Does this match your symptom?

Postgres connection or query path is failing

n8n cannot reach Postgres, a Postgres node fails in production, or self-hosted database settings are mixed up with workflow credentials.

First check: Separate whether n8n itself cannot start or only a workflow Postgres node cannot connect.

Problem Pattern

Users usually arrive here with a working SQL idea but an unclear production risk: the node may connect to the wrong database, fail from Docker networking, return too many rows, or write data without a rollback path.

Version awareness

Last reviewed 2026-05-23

Key Facts

Credential type
Postgres database connection credentials.
Common uses
Read operational data, write automation results, sync records, and trigger reporting workflows.
Key setup choice
Host, port, database, user, SSL, and query/operation mode.
Production risk
A successful test query does not prove safe permissions, bounded result size, or rollback behavior.
Common companion nodes
Schedule Trigger, IF, Set, Code, HTTP Request, and Slack.

Production Diagnostic Matrix

Turn checks into a brief
Exact symptom or log Likely cause First check Wrong fix to avoid Verification
getaddrinfo ENOTFOUND localhost or connect ECONNREFUSED 127.0.0.1:5432 The Postgres node is running inside the n8n container, so localhost points at the container instead of the database host. Check the credential host field and confirm whether Postgres is a Compose service, managed database, or external host. Do not expose Postgres publicly just to make localhost work. A tiny SELECT 1 query succeeds from the same n8n instance or worker that runs the workflow.
password authentication failed for user Wrong credential, wrong database user, rotated password, or the workflow is using the internal n8n database credential by mistake. Confirm the Postgres node credential name, database user, target database, and whether the password was recently rotated. Do not switch to a superuser credential to make the error disappear. The workflow credential connects with a least-privilege user and the intended query succeeds.
permission denied for table, schema, or sequence The database user can connect but lacks table, schema, sequence, or write permissions for the operation. Run a minimal query against the exact table and operation the workflow needs, not only SELECT 1. Do not grant broad admin permissions before identifying the specific missing privilege. The same user can read or write only the intended schema/table and cannot access unrelated tables.
self-signed certificate, SSL required, no pg_hba.conf entry, or SSL connection rejected Managed Postgres requires SSL or the node credential SSL setting does not match the server policy. Check the provider's SSL requirement and the Postgres node SSL setting before changing queries. Do not disable SSL on the database or bypass certificate checks without understanding the provider policy. The node connects with the provider-required SSL mode and still reaches the intended database.
Workflow times out or later nodes run out of memory after a successful query The query returns too many rows or large JSON/binary columns for n8n item processing. Add LIMIT, select only required columns, and estimate row count before passing data downstream. Do not increase memory first when the query can be bounded or paginated. The query returns a predictable row count and downstream nodes process within expected time.
Duplicate rows appear after retry, webhook replay, or manual re-run The workflow write is not idempotent and does not use a unique key or conflict strategy. Identify the business key and decide whether the workflow should insert, update, or upsert. Do not rely on manual execution discipline to prevent duplicate production writes. Re-running the same input updates the intended row or is safely ignored instead of creating a duplicate.
Works in manual execution but fails on active schedule, webhook, or queue worker The production execution runs on a different worker, network path, credential version, or environment than the manual test. Compare where manual and production executions run, especially queue workers and Docker network access. Do not edit SQL before proving the same runtime can reach the database. An active production execution from the real trigger succeeds with the same credential and query.

Still blocked after these checks?

Use the brief to decide whether to keep fixing this setup, move the workload to n8n Cloud, or rebuild the self-hosted path on cleaner infrastructure.

Compare tools
  1. Confirm whether this is a workflow Postgres node issue or n8n's own internal database connection issue.
  2. Create credentials for a database user with only the permissions this workflow needs.
  3. Choose the operation or query mode and avoid unsafe string concatenation in SQL.
  4. Test a low-risk SELECT with a small LIMIT before any write operation.
  5. Add handling for empty results, connection failures, duplicate writes, and large result sets.

Verification

  • The node connects to the intended database.
  • Queries return only the expected rows and columns.
  • Write operations can be rolled back or tested safely before production.
  • The workflow handles zero rows and connection errors without silently marking the business process complete.

First Commands / Checks

Resolve the database host from the n8n container Use when the credential host is a Docker Compose service name such as postgres.
docker compose exec n8n getent hosts postgres
Secrets note
This prints DNS resolution only; it should not expose passwords or tokens.
Verification
The command returns an IP address for the database service name.
Run a low-risk connectivity check from a private terminal Use when you need to separate credential/network failure from n8n node configuration.
psql "postgresql://workflow_user:REDACTED@postgres:5432/appdb?sslmode=require" -c "select current_database(), current_user;"
Secrets note
Replace REDACTED locally. Do not paste the real connection string into tickets, screenshots, or browser tools.
Verification
The result shows the expected database and least-privilege user.
Estimate result size before wiring downstream nodes Use before replacing a safe test query with a production SELECT.
select count(*) from orders where updated_at >= now() - interval '1 day';
Secrets note
Use neutral table names when sharing examples; remove customer-specific identifiers.
Verification
The count is small enough for one n8n execution or the workflow needs pagination/batching.
Smoke test an idempotent write pattern Use when a workflow may retry, replay webhook data, or be re-run manually.
insert into workflow_runs (source_id, status, updated_at)
values ('sample-source-id', 'checked', now())
on conflict (source_id)
do update set status = excluded.status, updated_at = excluded.updated_at
returning source_id, status;
Secrets note
Use sample IDs and a staging table until the production conflict key is confirmed.
Verification
Running the statement twice returns one logical row instead of creating duplicates.

Safe Copyable Config

Least-privilege Postgres role for workflow reads Use for workflows that read operational data but should never write or change schema.
-- Run as a database admin in a private session, then store the password only in n8n credentials.
create role workflow_reader login password 'REDACTED_CHANGE_LOCALLY';
grant usage on schema public to workflow_reader;
grant select on table public.orders to workflow_reader;
-- Optional: grant select on only the tables this workflow needs.
Bounded read pattern for n8n item processing Use before sending query results into IF, Set, Code, Slack, or HTTP Request nodes.
select id, email, status, updated_at
from public.orders
where updated_at >= now() - interval '1 day'
order by updated_at asc
limit 100;

Warnings

  • Do not use a broad admin database user for routine workflow operations.
  • Large result sets can create memory pressure in n8n.
  • A workflow Postgres credential is different from the Postgres database n8n may use internally.

Best For

  • Operational reads where n8n enriches, routes, or reports on existing database rows.
  • Small, bounded writes such as logging automation results, updating sync status, or inserting audit rows.
  • Production workflows that can use a least-privilege database role and clear verification queries.

Not For

  • Bulk ETL jobs that move large tables through n8n item memory.
  • Schema migrations, destructive maintenance, or ad hoc admin access from a workflow.
  • Queries that need secrets, customer payloads, or private hostnames pasted into node fields.

Common Mistakes

  • Using localhost from inside Docker when the database is another service or managed host.
  • Testing SELECT 1 and assuming the real query has enough table, schema, or write permissions.
  • Running an unbounded SELECT in production and pushing thousands of rows into later nodes.
  • Using the same admin credential for reads, writes, and schema changes.

Examples

Safe first Postgres node test Use a tiny read before debugging a complex production query.
Operation: Execute Query
Query: SELECT 1 AS n8n_connection_check;
Expected result: one row with n8n_connection_check = 1
If this fails: debug host, port, SSL, database, user, password, and network access before changing workflow logic.
Production query guardrails Add limits and expected fields before wiring data into downstream actions.
Use LIMIT on exploratory SELECT queries
Select only columns needed by later nodes
Handle zero rows as a valid branch
Test write operations on a staging table or reversible row
Document which database and schema the credential can access
Connection failure split Avoid mixing up workflow credentials with n8n infrastructure settings.
n8n will not start -> check DB_TYPE and DB_POSTGRESDB_* env vars
Only Postgres node fails -> check that node's credential, SSL, schema, and permissions
Queue worker fails -> check worker env, network, and database access too

Production Cookbook

Common production use cases

  • Read operational records for reports, routing, enrichment, and sync workflows.
  • Write small audit rows or sync status updates after external actions complete.
  • Use Postgres as a control table for idempotency, dedupe, and retry state.

Required credentials/scopes

  • A Postgres credential with host, port, database, user, password, and SSL mode matching the target database.
  • A least-privilege database role scoped to the exact schemas, tables, and operations the workflow needs.
  • Network access from every runtime that may execute the workflow, including queue workers.

Input fields that usually break

  • Host field when n8n runs in Docker; localhost usually means the n8n container.
  • SSL mode for managed Postgres providers.
  • Schema-qualified table names when search_path differs between users.
  • Dynamic SQL built from expressions without validation.
  • Unbounded SELECT queries and large JSON columns.

Common errors

  • ECONNREFUSED or ENOTFOUND from wrong host or Docker network assumptions.
  • password authentication failed from stale or wrong credentials.
  • permission denied for schema, table, or sequence.
  • SSL required or self-signed certificate errors.
  • Timeouts and memory pressure from returning too many rows.
  • Duplicate writes after retry because the query is not idempotent.
Output shape example
[
  {
    "id": 12345,
    "email_redacted": true,
    "status": "ready",
    "updated_at": "2026-05-23T10:15:00.000Z"
  }
]

Small working pattern

Start with SELECT current_database(), current_user, then query one schema-qualified table with explicit columns and LIMIT. For writes, use a staging table or an INSERT ... ON CONFLICT pattern before production activation.

When to use HTTP Request or Code instead: Use HTTP Request when the source system exposes a safer API than direct database access. Use Code to validate and reshape rows after the Postgres node, not to hide unsafe dynamic SQL construction.

FAQ

Why does the Postgres node fail in Docker when the same host works locally?

Inside Docker, localhost usually means the n8n container itself. Use the Compose service name, a reachable host address, or the managed database hostname that the container can access.

Should the workflow use the same Postgres user as n8n's internal database?

Usually no. A workflow node should use a database user scoped to the workflow's read or write needs, not the credential n8n uses to store its own data.

Why does the Postgres node work in a manual test but fail when the workflow is active?

Manual and active executions can run with different timing, input data, queue workers, or network paths. Check the production execution runtime, the exact input item, and whether workers can resolve and reach the same database host.

Sources