Skip to content
Wasevo
BlogHosting & Servers 18 min read

How to self-host n8n on a VPS with Docker and Postgres

How to self-host n8n on a VPS: server size from n8n's docs, Docker Compose with PostgreSQL and Caddy, firewall, backups with a restore test, updates and security.

Sami UllahSami UllahFull-stack Developer
Updated
How to self-host n8n on a VPS with Docker and Postgres

Summarize with:

Share:

To self-host n8n on a VPS, install Docker, run n8n and PostgreSQL with Docker Compose, put Caddy in front for HTTPS, open only ports 22, 80 and 443, and set up backups that you have restored once. The Community edition has no licence fee. You pay for the server and for keeping it updated, backed up and secure.

This guide builds that setup end to end on one Ubuntu server. Each command and variable comes from n8n's own documentation or from the Docker, Caddy, PostgreSQL and Ubuntu docs, checked on 13 November 2026. The section "How these commands were checked" says what was run and what was only read against the docs.

Key takeaways

  • n8n's hosting docs state no minimum server spec. They say memory matters more than CPU, so this guide starts at 2 vCPU and 4 GB RAM and shows how to check real usage.
  • Use PostgreSQL from the first day. n8n defaults to SQLite, and its Install using Docker Compose guide says to swap in Postgres for a production instance.
  • Set the firewall, point DNS, start Caddy, confirm the certificate, then create the owner account right away.
  • A backup is a PostgreSQL dump plus the encryption key. Restore it once on a spare machine before you rely on it.

What you take on when you self-host n8n

n8n's Docker Compose guide recommends self-hosting for expert users and warns that mistakes can lead to data loss, security issues and downtime. It sends people who do not manage servers to n8n Cloud. The licence is covered in Is n8n free?, and plan prices are in n8n pricing explained.

How big a VPS do you need to self-host n8n?

Start with 2 vCPU, 4 GB RAM and SSD storage, then measure. n8n's hosting documentation states no minimum specification for a self-hosted server, so treat this size as the guide's own starting point. The table shows what n8n's documentation says about each resource.

ResourceWhat n8n's docs sayWhat it means for your server
MemoryNeeds depend on your workflows and their data. An idle n8n Cloud instance uses about 100 MB. The Code node copies data before and after it runs, and large binary files can use all available memory.Memory is the resource most likely to run out. Check it after a week of real use.
CPUn8n is not CPU intensive, and memory requirements usually exceed CPU requirements.Two vCPUs are enough to start.
Diskn8n stores credentials, past executions and workflows in its database and recommends SSD storage. By default it deletes executions older than 336 hours (14 days) or beyond 10,000 executions.Disk use follows how many executions you keep.

These figures come from n8n's OEM prerequisites page, which calls its numbers an illustrative example based on n8n Cloud. n8n's performance page reports a c5a.large machine with 4 GB of RAM and PostgreSQL running a short webhook workflow, and says a single instance can handle up to 220 executions per second. That is a ceiling for a trivial workflow, and n8n advises benchmarking your own workflows. A smaller server can carry light work, since n8n's Hetzner guide names the CPX11 type as enough for most usage levels.

After a week, look at real use:

bash
docker stats --no-stream
free -h
df -h /

If memory sits near the total, or the n8n logs show JavaScript heap out of memory, add RAM or rebuild the heavy workflow with sub-workflows that return only small results, as n8n's memory guide suggests. Provider prices change often, so this guide quotes none. Pick a provider by region, snapshot options and a supported Ubuntu LTS image. Docker's install page lists 26.04, 24.04 and 22.04 as of 13 November 2026.

How to self-host n8n on a VPS, step by step

Replace n8n.example.com with your own hostname and /opt/n8n with your project folder. Run the commands on the server unless a step says otherwise.

1. Prepare the server

Log in over SSH with a key, create a non-root user with sudo rights, and apply updates. Turn on automatic security updates, which Ubuntu provides through the unattended-upgrades package:

bash
sudo apt update && sudo apt upgrade -y
sudo apt install unattended-upgrades

Install Docker Engine and the Compose plugin from Docker's apt repository by following Docker's Ubuntu install page. Confirm both work, as n8n's guide does:

bash
docker --version
docker compose version

To run Docker without sudo, use n8n's two commands. They add your user to the docker group and apply the change to the current session. Members of that group have root-level access to the server, so add only yourself:

bash
sudo usermod -aG docker ${USER}
exec sg docker newgrp

2. Set the firewall before anything listens

Allow SSH first, so that enabling the firewall does not lock you out, then the two web ports. If SSH listens on another port, allow that port instead of 22.

bash
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

Ubuntu's ufw is disabled until you enable it, and its default incoming policy is deny. Ports 80 and 443 stay open because Caddy needs them to obtain and renew certificates. The HTTP challenge uses port 80 and the TLS-ALPN challenge uses port 443, according to the Caddy docs.

Docker does not respect ufw for published ports. Docker's documentation says traffic to a published container port is diverted before it reaches ufw's rules. The Compose file below therefore publishes only Caddy's two ports. n8n and PostgreSQL have no ports: entry, and Caddy reaches n8n over the internal Compose network.

3. Point DNS at the server

Create an A record for your n8n subdomain that points to the server's IPv4 address, as n8n's guide describes. Add an AAAA record only if the server answers on IPv6, because Caddy looks up both record types when it validates the hostname. Check the record from your own computer before you start anything:

bash
dig +short n8n.example.com A

The answer must be the server's IP address. Caddy's docs say to set DNS records properly before running Caddy so it can provision certificates.

4. Write the .env, Compose and Caddy files

Create the project folder and generate the secrets with openssl, so that no password appears on a command line or in your shell history. The umask makes the file readable only by you:

bash
sudo mkdir -p /opt/n8n && sudo chown "$USER": /opt/n8n
cd /opt/n8n
umask 077
cat > .env <<EOF
N8N_VERSION=<the number in the Current stable box>
N8N_HOSTNAME=n8n.example.com
GENERIC_TIMEZONE=Europe/Stockholm
POSTGRES_USER=n8n
POSTGRES_DB=n8n
POSTGRES_PASSWORD=$(openssl rand -hex 24)
RUNNERS_AUTH_TOKEN=$(openssl rand -hex 24)
N8N_ENCRYPTION_KEY=$(openssl rand -hex 32)
EOF

Replace the version placeholder with the number in the "Current stable" box on n8n's Use Docker Compose page, not the beta, and set your own timezone. Copy the whole .env file into your password manager now. It holds the encryption key.

Create compose.yaml. It runs n8n, a task runner, PostgreSQL 18 and Caddy, keeps data in named volumes, and caps each container's log size. It combines settings from n8n's Docker Compose guide, the withPostgres example in the n8n-hosting repository, n8n's Hetzner guide and its task runner and reverse proxy pages.

yaml
name: n8n

x-logging: &default-logging
  driver: json-file
  options:
    max-size: "10m"
    max-file: "3"

services:
  postgres:
    image: postgres:18
    restart: always
    logging: *default-logging
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
      POSTGRES_DB: ${POSTGRES_DB}
      PGDATA: /var/lib/postgresql/data
    volumes:
      - db_storage:/var/lib/postgresql/data
    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:${N8N_VERSION}
    restart: always
    logging: *default-logging
    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:?set POSTGRES_PASSWORD in .env}
      N8N_HOST: ${N8N_HOSTNAME}
      N8N_PORT: "5678"
      N8N_PROTOCOL: https
      N8N_EDITOR_BASE_URL: https://${N8N_HOSTNAME}/
      N8N_WEBHOOK_URL: https://${N8N_HOSTNAME}/
      N8N_PROXY_HOPS: "1"
      N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY:?set N8N_ENCRYPTION_KEY in .env}
      GENERIC_TIMEZONE: ${GENERIC_TIMEZONE}
      TZ: ${GENERIC_TIMEZONE}
      N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS: "true"
      N8N_RUNNERS_MODE: external
      N8N_RUNNERS_AUTH_TOKEN: ${RUNNERS_AUTH_TOKEN:?set RUNNERS_AUTH_TOKEN in .env}
      N8N_RUNNERS_BROKER_LISTEN_ADDRESS: 0.0.0.0
    volumes:
      - n8n_storage:/home/node/.n8n
    depends_on:
      postgres:
        condition: service_healthy

  n8n-runner:
    image: n8nio/runners:${N8N_VERSION}
    restart: always
    logging: *default-logging
    environment:
      N8N_RUNNERS_AUTH_TOKEN: ${RUNNERS_AUTH_TOKEN:?set RUNNERS_AUTH_TOKEN in .env}
      N8N_RUNNERS_TASK_BROKER_URI: http://n8n:5679
    depends_on:
      - n8n

  caddy:
    image: caddy:2
    restart: always
    logging: *default-logging
    environment:
      N8N_HOSTNAME: ${N8N_HOSTNAME}
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      - n8n

volumes:
  db_storage:
    name: n8n_db_storage
  n8n_storage:
    name: n8n_storage
  caddy_data:
    name: n8n_caddy_data
  caddy_config:
    name: n8n_caddy_config

A few settings need explaining. N8N_ENCRYPTION_KEY encrypts stored credentials. n8n generates a random key on first launch if you set none, so set your own from the first start. N8N_WEBHOOK_URL and N8N_PROXY_HOPS tell n8n it sits behind one reverse proxy at a public address. N8N_WEBHOOK_URL exists from n8n 2.30.0, and WEBHOOK_URL is its deprecated alias from 2.35.0. The N8N_RUNNERS_* lines run the Code node in a separate container. The pruning of old execution data is on by default in n8n, at 336 hours or 10,000 executions.

Create Caddyfile in the same folder. The flush_interval -1 line comes from n8n's Hetzner guide, and the Caddy docs describe a negative value as turning response buffering off:

code
{$N8N_HOSTNAME} {
	reverse_proxy n8n:5678 {
		flush_interval -1
	}
}

Check the files before you start anything. docker compose config stops with an error if a required variable such as the encryption key is empty:

bash
docker compose config -q && echo "compose file is valid"

5. Start the stack and confirm the certificate

bash
docker compose up -d
docker compose ps
docker compose logs caddy

Caddy requests the certificate on its first start. Confirm it from your own computer rather than trusting the log:

bash
echo | openssl s_client -connect n8n.example.com:443 -servername n8n.example.com 2>/dev/null | openssl x509 -noout -issuer -dates
curl -sS -o /dev/null -w '%{http_code}\n' https://n8n.example.com/healthz/readiness

The first command shows the certificate issuer and its start and end dates. The second should print 200. n8n's docs say /healthz/readiness returns 200 when the database is connected and migrated.

6. Create the owner account immediately

Open https://n8n.example.com/ and complete the owner setup. n8n's backup documentation says that on a fresh instance the first person to complete the owner setup screen becomes the owner. Do this straight after the certificate check. n8n removed basic auth and JWT login in version 1.0 and offers no supported way to switch the login screen off, so the owner account and its password protect the editor.

Certificate and DNS order

For a new hostname, nobody uses the address until you create the A record, and Caddy cannot validate the name until the record exists. The order is firewall, DNS record, Caddy start, certificate check, owner account, and only then any webhook registration with outside services, because those URLs contain the hostname.

If you recreate the stack repeatedly while testing, add acme_ca https://acme-staging-v02.api.letsencrypt.org/directory to a global options block at the top of the Caddyfile and remove it for the real start. Let's Encrypt allows 5 certificates per exact set of hostnames every 7 days. Keep the caddy_data volume, because Caddy's Docker image documentation says its data directory holds certificates and keys and is not a cache.

Moving an n8n instance that already serves traffic needs a valid certificate on the new server before you switch DNS. The server migration checklist covers that sequence, including the DNS-01 challenge and testing with curl --resolve.

How do you back up n8n and restore it?

A complete n8n backup has two required parts, the PostgreSQL database and the .n8n folder, according to n8n's backup documentation. The folder holds the configuration file, which stores the encryption key unless you supply N8N_ENCRYPTION_KEY yourself. This guide supplies it, so the key lives in your .env file. Without the key, a restored database cannot be decrypted.

WhatHow this guide saves it
PostgreSQL databasepg_dump in custom format, nightly
.env file with the key and passwordsCopy into a password manager, and again whenever it changes
n8n_storage volume (the .n8n folder)Archive with tar
compose.yaml and CaddyfileKeep in a private Git repository

Save this as /opt/n8n/backup.sh and make it executable with chmod 700. It writes the dump to a temporary name first, so a failed run does not leave a truncated file that looks valid:

bash
#!/usr/bin/env bash
set -euo pipefail
umask 077
cd /opt/n8n
stamp=$(date -u +%Y%m%dT%H%M%SZ)
mkdir -p backups

# 1. PostgreSQL dump in custom format, written to a temp name first
docker compose exec -T postgres sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' \
  > "backups/n8n-db-$stamp.dump.partial"
mv "backups/n8n-db-$stamp.dump.partial" "backups/n8n-db-$stamp.dump"

# 2. The .n8n folder (config file, logs) from the n8n_storage volume
docker run --rm -v n8n_storage:/data:ro -v "$PWD/backups":/backup alpine:3 \
  tar czf "/backup/n8n-data-$stamp.tgz" -C /data .

# 3. Example retention: delete local copies older than 14 days
find backups -type f -mtime +14 -delete

# 4. Copy backups/ to storage outside this server here, encrypted

The script runs pg_dump inside the container, which needs no password because the official PostgreSQL image trusts local connections from inside the container. Schedule it with crontab -e as the user that owns /opt/n8n. The log file sits in /opt/n8n, because a non-root user cannot write to /var/log:

code
0 2 * * * /opt/n8n/backup.sh >> /opt/n8n/backup.log 2>&1

Check the next morning that a new .dump file exists and is not empty. The dumps hold your execution data, which may include customer information, so the umask keeps them private and any off-server copy should be encrypted. The off-server copy in the script matters as much as the dump, because a backup that stays on the VPS is lost with the VPS.

n8n's CLI can also export workflows and credentials as JSON with n8n export:workflow --backup and n8n export:credentials --backup. These exports contain no users, execution history, variables or instance settings, so they cannot recover a full instance.

Restore the instance

Run this on a spare server first. Check which server you are on before you start, because these commands replace the database in the current stack. Before the restore:

  1. Install Docker on the spare server and copy over compose.yaml, Caddyfile, .env and one dump.
  2. Set N8N_HOSTNAME in that .env to a test subdomain, create its A record, and confirm with dig +short that it returns the spare server's address. Caddy starts with the stack and needs that record to issue a certificate.

Then run:

bash
cd /opt/n8n
docker compose up -d postgres
docker compose stop n8n
docker compose exec -T postgres sh -c 'dropdb -U "$POSTGRES_USER" --if-exists "$POSTGRES_DB" && createdb -U "$POSTGRES_USER" "$POSTGRES_DB"'
docker compose exec -T postgres sh -c 'pg_restore -U "$POSTGRES_USER" -d "$POSTGRES_DB" --exit-on-error' < backups/n8n-db-STAMP.dump
docker compose run --rm --no-deps n8n unpublish:workflow --all
docker compose up -d

Replace STAMP with the timestamp of the dump. The unpublish line is for the test only. A restored copy that holds live credentials would otherwise run your scheduled workflows and send duplicate emails or messages. Leave it out when you recover a real instance.

If you also lost the .n8n folder, unpack its archive into the volume before the last command:

bash
docker run --rm -v n8n_storage:/data -v "$PWD/backups":/backup alpine:3 tar xzf /backup/n8n-data-STAMP.tgz -C /data

Then prove the restore worked. Sign in, open a workflow that uses a credential and run it. If the credential fails to decrypt, the N8N_ENCRYPTION_KEY in the restored .env differs from the one that encrypted the data. Repeat the test after you change the backup script and on a regular schedule, for example every quarter.

How do you update a self-hosted n8n?

n8n releases a new minor version most weeks and advises updating at least once a month, so you jump fewer versions at a time. Pin an exact image tag instead of latest, which is what N8N_VERSION does. The n8nio/runners image uses the same variable because n8n requires its version to match the n8nio/n8n image.

  1. Read the release notes for every version between yours and the target, looking for breaking changes.
  2. Run /opt/n8n/backup.sh and confirm the new dump exists.
  3. Edit N8N_VERSION in .env.
  4. Update with the commands from n8n's guide:
bash
cd /opt/n8n
docker compose pull
docker compose down
docker compose up -d
  1. Run docker compose ps, call /healthz/readiness, and run one real workflow.

Never add -v to docker compose down. It deletes the named volumes, including the database and the .n8n folder.

For a rollback, n8n's queue-mode update guide says that setting the image tag back does not reverse database migrations. n8n runs pending migrations whenever a process starts, so treat the pre-update backup as the way back on a single instance too. Do not raise the postgres image tag casually, because PostgreSQL 18 cannot read a data directory written by version 16 and the n8n-hosting repository documents a dump-and-restore path.

Monitoring

n8n's /healthz endpoint returns 200 when the instance is reachable but says nothing about the database. /healthz/readiness returns 200 only when the database is connected and migrated. Point an external uptime check at https://n8n.example.com/healthz/readiness, which also reveals an expired certificate.

For failed workflows, create a workflow that starts with the Error Trigger node and sends you an email or chat message, then select it as the error workflow in each workflow's settings. n8n's docs say one error workflow can serve many workflows. Run df -h / now and then, because the Compose file caps container logs and n8n prunes old executions, but neither limits other disk use.

Security basics for a public n8n editor

  • Create the owner account at once and turn on two-factor authentication under Settings, Profile and preferences. n8n supports authenticator apps. SSO is not part of the Community edition.
  • Keep the task runner. n8n's task runner page says to always use task runners in production, because without external mode anyone who can edit a workflow could potentially read the database, encryption key, credentials and environment variables.
  • Webhook URLs are public by design. The Webhook node can require basic auth, header auth or JWT auth, so enable one of them on any webhook that triggers something sensitive.
  • Keep .env at mode 600, out of Git and out of screenshots. Anyone who holds the encryption key and a database copy can read your credentials.
  • If you do not use n8n's REST API, n8n recommends disabling it. Add N8N_PUBLIC_API_DISABLED: "true" to the n8n environment block.
  • Keep automatic security updates on and use SSH keys. Before you disable password logins, keep your current session open, log in again from a second terminal with the key, and only then switch passwords off. Hosting and server management covers this server work.

Queue mode

Queue mode adds Redis and worker processes for higher load. n8n publishes no execution threshold for it. Its pricing page lists queue mode under Business while its edition docs include it in Community, and Is n8n free? explains the conflict. Ask n8n before you rely on it.

How these commands were checked

On 13 November 2026, docker compose config accepted the Compose file above with Docker Compose v2.40, and it stopped with "required variable POSTGRES_PASSWORD is missing a value" when the .env file was absent. The flags used with docker compose run and docker compose exec were confirmed with their --help output. The .env creation with openssl rand ran locally, bash -n accepted the backup script, and the dig, openssl s_client and curl commands ran against an unrelated public site to confirm their syntax. No Docker daemon was running, so the containers were never started. The stack, the Caddyfile, the certificate request, the backup script, the cron line, the restore commands and the firewall rules were not run. They follow the linked documentation. Test them on a throwaway server first, and treat the restore test as part of the setup.

Next step

If you want n8n built on a server you own and kept current by someone else, see n8n automation services, which lists self-hosted installation and backups, and hosting and server management. Wasevo lists n8n and Docker among the platforms it works with.

Frequently asked questions

Yes. n8n's Community edition is free, runs without a licence key and has almost the complete feature set. You still pay for the server, backups and your own time. The licence allows internal business use, and Is n8n free? explains the limits.

Sami Ullah

Written by

Sami Ullah

Full-stack Developer at Wasevo. Writes about web and app builds, hosting, migrations, WHMCS and keeping servers healthy.

Related articles

Get new guides by email

One short email when we publish something useful. No spam; unsubscribe at any time.

Servers · Migrations · Maintenance

Keep it fast, backed up and updated.

Book a free call

15 minutes, no sales pitch