How to Self-Host N8n: Step-By-Step Setup Guide

Published:

Can your automation receive a customer inquiry after you close your laptop? A local installation is useful for learning, but unattended workflows need somewhere that stays on.

Moving n8n onto your own hardware also means taking care of credentials, updates and backups. Getting the editor to open is only part of the job, and losing a workflow is a miserable way to discover the rest.

I use self-hosted n8n to connect my business tools without code. This guide covers the installation and the checks that make it useful: private access, public HTTPS where needed, a working automation and a recovery test.

Step 1: Choose Where to Run n8n

Choose your host based on when your workflows need to run and what needs to reach them.

Hosting LocationAvailabilityExternal Webhook AccessExpensesMaintenance Responsibility
Your computerRuns while the computer is awake and Docker is runningPrivate in this guideExisting hardware, electricity and any paid services your workflows callYou manage Docker, updates and backups
A VPSRuns independently of your computer while the server and services are availablePublic HTTPS address configured in Step 5Server rental, backups, domain renewal and connected servicesYou manage the operating system, Docker, security and recovery

A VPS is a rented virtual server. I would use one for customer inquiries, scheduled reports or anything that needs to work while my computer is off. Start locally if you want to learn before paying for hosting.

A home server can also work, but its availability depends on your home power and internet connection. Receiving public webhooks adds router and network setup.

For a modest starting server, I would consider 2 vCPUs and 4 GiB of RAM, then watch actual usage. DigitalOcean’s Basic Regular Droplet with that allocation and an 80 GiB SSD is listed at $24 per month before extras. That is a budgeting example for light workflows, and larger files or several simultaneous executions can need more resources. Check DigitalOcean’s pricing before ordering.

Step 1: Choose Where To Run N8N: Where Should You Host N8N?; Local Computer: Learn Privately; Computer Awake + Docker Running; Computer Off → Automation Stops; Vps: Run Independently; Server And Services Must Stay Available; Public Https For

Include off-server backups, domain renewal and API usage in your budget. Self-hosting n8n does not make the services it calls free.

Community edition suits personal use and internal business automation under n8n’s Sustainable Use License. Selling hosted access to n8n requires a separate licensing check.

Also check how your team works before replacing a subscription. Community edition does not include ordinary workflow and credential sharing between users, so it may not replace your existing collaboration setup. See the edition differences.

Throughout this guide, imagine you sell printable sewing patterns. You will record a test customer inquiry in a spreadsheet. Keep real customer data out of the installation until its security and recovery checks pass.

Step 2: Install Docker on Your Computer or Server

Docker runs each service in a container. Compose reads one configuration file and starts those services together.

Follow the preparation section for your chosen host. All shell commands use Bash on macOS, Linux or Windows through WSL.

Prepare a Local Computer

Install Docker Desktop and start it. On Windows, use its WSL2 backend and run the commands inside your WSL Linux terminal. Keep the project in the Linux filesystem, such as ~/n8n.

Check that Docker can reach its running engine:

docker version
docker compose version

The first command should show both client and server information. If it only shows the client and a connection error, start Docker Desktop before continuing.

Create your project directory:

mkdir -p ~/n8n
cd ~/n8n

Prepare an Ubuntu Server

Provision a fresh Ubuntu 24.04 LTS server with SSH-key access. In the provider’s firewall, allow SSH from your administration IP and keep public application ports closed for now.

Use an administrator account that can run commands with sudo, which grants administrator privileges for that command. If you initially connected as root and need to create one, these commands create an automation user and copy the existing root login key:

adduser automation
usermod -aG sudo automation

install -d -m 700 -o automation -g automation \
  /home/automation/.ssh

install -m 600 -o automation -g automation \
  /root/.ssh/authorized_keys \
  /home/automation/.ssh/authorized_keys

Open a second terminal and confirm you can connect as that user before closing your original session:

ssh automation@YOUR_SERVER_IP
sudo -v
Prepare An Ubuntu Server: Prepare Private Access To Your N8N Server; Ssh Automation@Your_Server_Ip; Ssh: Administration Ip Only; Sudo -V; Verify The New Administrator First; Update Ubuntu; Install And Verify Docker; Public Application Ports Stay

Run the remaining server commands as this administrator. Apply operating-system updates, and reboot if the server requests it:

sudo apt update
sudo apt upgrade -y

Install Docker from its official Ubuntu repository. The following uses the repository for Ubuntu 24.04:

sudo apt install -y ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings

sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
  -o /etc/apt/keyrings/docker.asc

sudo chmod a+r /etc/apt/keyrings/docker.asc

sudo tee /etc/apt/sources.list.d/docker.sources > /dev/null <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: noble
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF

sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io \
  docker-buildx-plugin docker-compose-plugin

sudo systemctl enable --now docker
sudo docker run --rm hello-world
sudo docker compose version

Docker-published ports can bypass UFW rules. Use the private port mapping below and your provider’s firewall to control exposure, as described in Docker’s Ubuntu installation guidance.

Create the project directory:

mkdir -p ~/n8n
cd ~/n8n

For the shared instructions below, commands use docker compose. On Ubuntu, use sudo docker compose instead. Apply the same rule to other Docker commands, such as docker inspect and docker run.

Step 3: Create the Docker Compose Configuration

This installation has three services:

  • postgres: Stores workflows, credentials, users and other application records.
  • n8n: Provides the editor and runs workflows.
  • n8n-runner: Runs JavaScript or Python from a workflow’s Code nodes in a separate container.
Step 3: Create The Docker Compose Configuration: The Three Services In Your N8N Installation; Private Compose Network; Postgres; Workflows, Credentials And Users; N8N; Editor And Workflow Execution; N8N-Runner; Javascript And Python Code Nodes

Named Docker volumes preserve data when containers are replaced.

Create three files inside ~/n8n: compose.yaml, .env and init-data.sh. A plain-text editor is enough.

Configure PostgreSQL and Persistent Storage

Save this complete configuration as compose.yaml:

services:
  postgres:
    image: postgres:18
    restart: unless-stopped
    environment:
      POSTGRES_USER: ${POSTGRES_USER:?Set POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB:?Set POSTGRES_DB}
      POSTGRES_NON_ROOT_USER: ${POSTGRES_NON_ROOT_USER:?Set application user}
      POSTGRES_NON_ROOT_PASSWORD: ${POSTGRES_NON_ROOT_PASSWORD:?Set application password}

      # Keep the data directory and volume mount aligned.
      PGDATA: /var/lib/postgresql/data
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./init-data.sh:/docker-entrypoint-initdb.d/init-data.sh:ro
    healthcheck:
      test:
        - CMD-SHELL
        - pg_isready -h 127.0.0.1 -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"
      interval: 5s
      timeout: 5s
      retries: 20

  n8n:
    image: docker.n8n.io/n8nio/n8n:${N8N_VERSION:?Set N8N_VERSION}
    restart: unless-stopped
    depends_on:
      postgres:
        condition: service_healthy
    ports:
      # Available only through this machine's loopback address.
      - "127.0.0.1:5678:5678"
    environment:
      DB_TYPE: postgresdb
      DB_POSTGRESDB_HOST: postgres
      DB_POSTGRESDB_PORT: "5432"
      DB_POSTGRESDB_DATABASE: ${POSTGRES_DB}
      DB_POSTGRESDB_USER: ${POSTGRES_NON_ROOT_USER}
      DB_POSTGRESDB_PASSWORD: ${POSTGRES_NON_ROOT_PASSWORD}

      N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY:?Set encryption key}
      N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS: "true"
      GENERIC_TIMEZONE: ${GENERIC_TIMEZONE}
      TZ: ${TZ}

      N8N_HOST: ${N8N_HOST}
      N8N_PROTOCOL: ${N8N_PROTOCOL}
      N8N_PORT: "5678"
      N8N_EDITOR_BASE_URL: ${N8N_EDITOR_BASE_URL}
      N8N_WEBHOOK_URL: ${N8N_WEBHOOK_URL}
      N8N_PROXY_HOPS: ${N8N_PROXY_HOPS}
      N8N_SECURE_COOKIE: ${N8N_SECURE_COOKIE}

      N8N_RUNNERS_MODE: external
      N8N_RUNNERS_BROKER_LISTEN_ADDRESS: "0.0.0.0"
      N8N_RUNNERS_AUTH_TOKEN: ${N8N_RUNNERS_AUTH_TOKEN:?Set runner token}

      EXECUTIONS_DATA_PRUNE: "true"
    volumes:
      - n8n_data:/home/node/.n8n

  n8n-runner:
    image: n8nio/runners:${N8N_VERSION}
    restart: unless-stopped
    depends_on:
      - n8n
    environment:
      N8N_RUNNERS_TASK_BROKER_URI: http://n8n:5679
      N8N_RUNNERS_AUTH_TOKEN: ${N8N_RUNNERS_AUTH_TOKEN}
      HOME: /tmp
    user: "65532:65532"
    read_only: true
    tmpfs:
      - /tmp:size=256m,mode=1777
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true

volumes:
  postgres_data:
  n8n_data:

PostgreSQL and the task runner have no published ports. n8n waits for PostgreSQL’s health check before starting.

Configure Postgresql And Persistent Storage: Where Your Self-Hosted N8N Data Lives; /Var/Lib/Postgresql/Data; Postgres_Data; Application Records; /Home/Node/.N8N; N8N_Data; Application Files; Replacing Containers Preserves Named Volumes; Down -V

The database layout follows n8n’s official PostgreSQL Compose example, with private access and additional runner restrictions.

Now save this as init-data.sh:

#!/bin/sh
set -eu

# Create an application login without giving it PostgreSQL superuser access.
psql \
  --username "$POSTGRES_USER" \
  --dbname "$POSTGRES_DB" \
  --set=ON_ERROR_STOP=1 \
  --set=app_role="$POSTGRES_NON_ROOT_USER" \
  --set=app_password="$POSTGRES_NON_ROOT_PASSWORD" \
  --set=app_database="$POSTGRES_DB" <<'SQL'
CREATE ROLE :"app_role" LOGIN PASSWORD :'app_password';
GRANT ALL PRIVILEGES ON DATABASE :"app_database" TO :"app_role";
GRANT USAGE, CREATE ON SCHEMA public TO :"app_role";
SQL

Save shell files with Unix line endings. The initialization script runs when PostgreSQL first creates an empty data directory.

Use fresh volumes for this installation. Changing database settings does not move an existing SQLite database into PostgreSQL. If you already have an instance, preserve it and plan its migration separately.

Set Secrets and Timezones

Generate four separate secrets. Run this command once for each database password, once for the encryption key and once for the runner token:

openssl rand -hex 32

Save the following as .env, replacing all four REPLACE_... values with different generated secrets:

# Both application images use this exact version.
N8N_VERSION=2.45.7

# PostgreSQL administrator and application login.
POSTGRES_USER=postgres
POSTGRES_PASSWORD=REPLACE_ADMIN_DATABASE_PASSWORD
POSTGRES_DB=n8n
POSTGRES_NON_ROOT_USER=n8n_app
POSTGRES_NON_ROOT_PASSWORD=REPLACE_APPLICATION_DATABASE_PASSWORD

# Keep the encryption key for the lifetime of this instance.
N8N_ENCRYPTION_KEY=REPLACE_ENCRYPTION_KEY
N8N_RUNNERS_AUTH_TOKEN=REPLACE_RUNNER_TOKEN

GENERIC_TIMEZONE=Asia/Kolkata
TZ=Asia/Kolkata

# Private HTTP access for initial setup.
N8N_HOST=localhost
N8N_PROTOCOL=http
N8N_EDITOR_BASE_URL=http://localhost:5678/
N8N_WEBHOOK_URL=http://localhost:5678/
N8N_PROXY_HOPS=0
N8N_SECURE_COOKIE=false

Choose your intended timezone. A workflow’s own timezone takes precedence when one is set.

Set Secrets And Timezones: N8N Credentials Need Their Original Encryption Key; Database Backup; Original N8N_Encryption_Key; Credentials Can Be Decrypted; Backup Without The Original Key; Credentials Cannot Be Recovered For Use; Keep A Protected Key

Protect the file:

chmod 600 .env
chmod 644 init-data.sh

Add these lines to the project’s .gitignore if you use Git:

.env
backups/

The .env file holds plaintext secrets. Save a protected copy of the encryption key outside the server, such as in your password manager. A database backup cannot recover usable credentials without the original key. This is how n8n’s credential encryption works.

Also notice that every container setting appears under its service’s environment section. Putting a value in .env supplies a substitution for Compose; it does not automatically pass that value into every container.

Configure the External Task Runner

The Compose file already configures external mode. n8n listens for runner connections on the private Compose network, and the runner connects to http://n8n:5679 using the shared token.

Both images use the same pinned version. The example uses n8n 2.45.7, and Step 8 explains how to change versions together.

Configure The External Task Runner: How N8N Isolates Code Execution; Http://N8N:5679; Shared Runner Token; Unprivileged User; Read-Only Filesystem; Writable /Tmp; No Database Passwords, Encryption Key Or N8N Volume; Keep N8N And Runner Versions

The runner receives neither database passwords nor the encryption key. It also has no access to n8n’s persistent directory.

Its unprivileged user, read-only filesystem and writable /tmp follow n8n’s runner-hardening guidance. Leave those boundaries in place when adding workflows.

Step 4: Start n8n and Secure the Owner Account

From ~/n8n, validate the configuration and start the services:

docker compose config --quiet
docker compose up -d
docker compose ps
docker compose logs --tail=80 postgres n8n n8n-runner

On Ubuntu, prefix these Docker commands with sudo.

PostgreSQL should become healthy, and n8n and its runner should stay running. If a container repeatedly restarts, resolve that before continuing.

For a local installation, open:

http://localhost:5678

For a server, open a separate terminal on your computer and create an SSH tunnel:

ssh -N -L 5678:127.0.0.1:5678 automation@YOUR_SERVER_IP

Keep that terminal open, then visit the same localhost address in your browser. The tunnel carries your connection to the server’s private n8n port.

Create the instance owner account with a unique password. This account belongs to your installation and is separate from an n8n Cloud account.

Enable two-factor authentication in your personal settings, connect an authenticator app and save the recovery codes.

Next, connect an email service so n8n can send password-reset messages. It uses SMTP, the standard protocol for sending email. Add these entries under the existing n8n.environment section in compose.yaml:

N8N_EMAIL_MODE: smtp
N8N_SMTP_HOST: ${N8N_SMTP_HOST}
N8N_SMTP_PORT: ${N8N_SMTP_PORT}
N8N_SMTP_USER: ${N8N_SMTP_USER}
N8N_SMTP_PASS: ${N8N_SMTP_PASS}
N8N_SMTP_SENDER: ${N8N_SMTP_SENDER}
N8N_SMTP_SSL: ${N8N_SMTP_SSL}

Add matching values to .env using your email provider’s SMTP settings. For example, a provider using implicit TLS on port 465 would look like this:

N8N_SMTP_HOST=smtp.example.com
N8N_SMTP_PORT=465
N8N_SMTP_USER='REPLACE_SMTP_USERNAME'
N8N_SMTP_PASS='REPLACE_SMTP_PASSWORD'
N8N_SMTP_SENDER='Automation <[email protected]>'
N8N_SMTP_SSL=true

Use your provider’s required port and TLS mode. Single quotes keep characters such as $ literal in .env values.

Apply the changes:

docker compose config --quiet
docker compose up -d n8n

Test a password-reset email and confirm its link opens the correct instance. Without SMTP, email password resets are unavailable, as explained in n8n’s self-hosted user-management guidance.

For a routine shutdown, use:

docker compose stop

Avoid docker compose down -v unless you intend to delete the project’s persistent volumes.

Step 5: Add a Domain and HTTPS for Server Hosting

Complete this step before connecting external services to a public server. Local-only installations can continue to Step 6.

Caddy will receive public HTTPS requests and forward them to n8n over the private Compose network. This makes Caddy the reverse proxy.

Point a Subdomain to the Server

Create an A record for an unused hostname, such as n8n.example.com, pointing to your server’s public IPv4 address.

Use direct DNS for this configuration. If you manage DNS through Cloudflare, set this record to DNS only.

Check the result from your computer:

nslookup n8n.example.com

The result should show your server’s IPv4 address. Remove conflicting records. An AAAA record points to an IPv6 address; add one only if IPv6 works on the server.

In the provider firewall, allow inbound TCP ports 80 and 443. Keep SSH restricted to your administration IP and leave port 5678 closed publicly.

Configure Caddy and n8n’s Public URLs

Inside ~/n8n, create a configuration directory:

mkdir -p caddy

Save this as caddy/Caddyfile, replacing the hostname:

n8n.example.com {
    reverse_proxy n8n:5678
}

Create a new file named compose.override.yaml beside compose.yaml:

services:
  caddy:
    image: caddy:2
    restart: unless-stopped
    depends_on:
      - n8n
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./caddy:/etc/caddy:ro
      - caddy_data:/data
      - caddy_config:/config

volumes:
  caddy_data:
  caddy_config:

Compose automatically includes this override file during normal commands. Caddy’s /data volume preserves certificate information.

When the hostname resolves correctly and public ports are reachable, Caddy obtains and renews certificates automatically. See its HTTPS reverse-proxy requirements.

Configure Caddy And N8N’s Public Urls: How Caddy Routes Public Https To N8N; Https://N8N.example.com; Public Tcp 80 And 443 Allowed; Caddy: One Reverse Proxy; N8N_Proxy_Hops=1; Reverse_Proxy N8N:5678; Internal N8N Port: 5678; No Public Access To

Replace the local-access values in .env with:

N8N_HOST=n8n.example.com
N8N_PROTOCOL=https
N8N_EDITOR_BASE_URL=https://n8n.example.com/
N8N_WEBHOOK_URL=https://n8n.example.com/
N8N_PROXY_HOPS=1
N8N_SECURE_COOKIE=true

Keep n8n’s internal port at 5678 in Compose.

The proxy-hop value is one because requests pass directly through one Caddy instance. Caddy supplies the forwarded client, host and protocol headers needed for this arrangement. The public webhook setting tells n8n which address external services should use, following n8n’s reverse-proxy configuration.

Apply the configuration:

docker compose config --quiet
docker compose up -d
docker compose logs --tail=80 caddy

Open https://n8n.example.com from another network, such as your phone’s mobile connection. Confirm that:

  • The certificate is trusted.
  • The n8n login screen appears.
  • http://YOUR_SERVER_IP:5678 is inaccessible.

You can now close the setup tunnel and use the HTTPS address.

Step 6: Verify a Working Automation

Check the whole journey: input enters n8n, a Code node runs, credentials work and the destination receives the expected data.

I once caught a field-mapping mistake in a digital-product workflow after the execution had finished successfully. The connection worked, but the destination contained the wrong value. Since then, I check what arrived before trusting the green success indicator.

Test Credentials and Persistence

Create a Google spreadsheet with these column headers:

inquiry_id | customer_name | question

Build this workflow:

Manual Trigger → Edit Fields → Code → Google Sheets

In Edit Fields, add three string fields:

FieldTest Value
inquiry_idTEST-001
customer_nameAlex
questionDoes this pattern include seam allowances?

Set the Code node to JavaScript and “Run Once for All Items,” then enter:

return $input.all();

This deliberately simple script checks that the external runner can execute a task.

This example uses OAuth to let n8n access Google Sheets with your permission, without storing your Google password. On self-hosted n8n, you must create your own OAuth client—the app Google recognizes when you grant that access. Create a Google Cloud project, enable the Google Sheets and Google Drive APIs, and configure the OAuth consent screen. If the app is in testing mode, add your Google account as a test user.

Test Credentials And Persistence: Prove Your N8N Workflow Survives A Restart; Manual Trigger; Edit Fields; Code; Google Sheets; Return $Input.all();; Test-001 → First Row Confirmed; Save, Then Restart N8N And Runner; Inquiry_Id; Test-001; Test-002

Then:

  1. Create a Google Sheets OAuth credential in n8n and copy its callback URL. This is the address Google returns you to after you grant access.
  2. In Google Cloud, create an OAuth client with the Web application type.
  3. Register that exact callback as an authorized redirect URI.
  4. Copy the client ID and secret into the n8n credential.
  5. Connect your Google account and approve the required access.

These requirements come from n8n’s Google OAuth setup for self-hosted installations. Use a test account with access only to the data needed for this check.

In the Google Sheets node, choose Append Row, select the test spreadsheet and map each incoming field to its matching column.

Execute the workflow and open Google Sheets. Confirm that TEST-001, Alex and the complete question appear in one row.

Save the workflow, then restart the application services:

docker compose restart n8n n8n-runner

Reopen the workflow, change the inquiry ID to TEST-002 and execute it again. Confirm that the saved workflow and credential still work and that a second row appears.

Before relying on Google OAuth for unattended work, resolve its testing status. For an external OAuth app left in Testing, Google issues seven-day refresh tokens when you request permissions such as Sheets access. These tokens let n8n stay connected without another login, so their expiry can interrupt your workflow. See Google’s token-expiration rules and complete the publishing or verification requirements that apply to your app.

For imported workflows, reconnect credentials and check callback URLs before testing. Keep passwords and API tokens in credential records, away from node text and shared exports.

Test a Public Webhook

On the HTTPS server, replace Manual Trigger with a Webhook node.

Set its method to POST and its path to sewing-inquiry. Choose Header Auth and create a credential with:

  • Header Name: X-Inquiry-Key
  • Header Value: A new, randomly generated secret

The owner login protects the editor. This header separately protects the webhook endpoint.

Test A Public Webhook: N8N Webhooks: Test Vs Production; Test Endpoint; Listen For Test Event; /Webhook-Test/Sewing-Inquiry; Test-003; Temporary Listener; Save And Publish The Workflow; Production Endpoint; Use The Node’s Production Url; Test-004

In Edit Fields, replace the fixed test values with expressions that read the request body:

inquiry_id:    {{ $json.body.inquiry_id }}
customer_name: {{ $json.body.customer_name }}
question:      {{ $json.body.question }}

Choose Listen for test event. From a computer outside the server, send this request using the exact test URL shown by your node:

curl --fail-with-body \
  --request POST \
  'https://n8n.example.com/webhook-test/sewing-inquiry' \
  --header 'Content-Type: application/json' \
  --header 'X-Inquiry-Key: REPLACE_WITH_YOUR_HEADER_SECRET' \
  --data '{
    "inquiry_id": "TEST-003",
    "customer_name": "Alex",
    "question": "Does this pattern include seam allowances?"
  }'

Confirm the spreadsheet row.

Next, save and publish the workflow. Close the editor, change the request to use the node’s Production URL and send another inquiry with ID TEST-004. Confirm both the execution record and the new spreadsheet row.

The test listener is temporary; the production endpoint works only while the workflow is published.

Local installations can stay private when manual, scheduled or local triggers meet your needs. An external service needs a reachable endpoint to deliver a webhook.

Step 7: Back Up n8n and Test Recovery

Create a Complete Backup

For this installation, a complete backup needs:

  • Database: A PostgreSQL dump containing application records.
  • Application Files: The contents of the volume mounted at /home/node/.n8n.
  • Recovery Key: The original N8N_ENCRYPTION_KEY, included in your protected .env copy.
  • Deployment Files: Compose files, .env, the initialization script and Caddy configuration.

Workflow JSON exports alone cannot restore the full instance. n8n’s backup requirements include both the application directory and the external database.

Pause incoming events before taking the backup. For the sewing-pattern test, stop sending requests. For a real workflow, pause its source or arrange for events to queue and retry during the maintenance window.

The following Bash block is for Ubuntu and includes sudo. On Docker Desktop, remove sudo from the Docker commands. Run it from the project directory:

(
  set -euo pipefail
  umask 077

  backup_dir="$HOME/n8n-backups/$(date +%Y%m%d-%H%M%S)"
  mkdir -p "$backup_dir"

  # Download the archive utility before stopping the application.
  sudo docker pull ubuntu:24.04

  n8n_container=$(sudo docker compose ps -a -q n8n)
  test -n "$n8n_container"

  # Discover the mounted volume instead of guessing its project prefix.
  n8n_volume=$(sudo docker inspect \
    --format '{{range .Mounts}}{{if eq .Destination "/home/node/.n8n"}}{{.Name}}{{end}}{{end}}' \
    "$n8n_container")
  test -n "$n8n_volume"

  sudo docker compose stop n8n n8n-runner
  trap 'sudo docker compose start n8n n8n-runner' EXIT

  # PostgreSQL stays running so pg_dump can read the database.
  sudo docker compose exec -T postgres sh -c \
    'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' \
    > "$backup_dir/postgres.dump"

  # Archive n8n's stopped application volume, retaining ownership.
  sudo docker run --rm \
    --mount "type=volume,src=$n8n_volume,dst=/data,readonly" \
    ubuntu:24.04 \
    tar --numeric-owner -czpf - -C /data . \
    > "$backup_dir/n8n-data.tar.gz"

  deployment_files=(compose.yaml .env init-data.sh)

  if [ -f compose.override.yaml ]; then
    deployment_files+=(compose.override.yaml)
  fi

  if [ -d caddy ]; then
    deployment_files+=(caddy)
  fi

  tar -czpf "$backup_dir/deployment.tar.gz" \
    "${deployment_files[@]}"

  sudo docker compose images > "$backup_dir/images.txt"

  sudo docker compose exec -T postgres postgres --version \
    > "$backup_dir/postgres-version.txt"

  test -s "$backup_dir/postgres.dump"
  test -s "$backup_dir/n8n-data.tar.gz"

  printf 'Backup saved to %s\n' "$backup_dir"
)
Create A Complete Backup: A Complete Backup For This N8N Setup; 1. Postgresql Dump; Application Records; 2. Application Files; /Home/Node/.N8N; 3. Original Encryption Key; Protected .Env Copy; 4. Deployment Files; Compose, .Env, Init Script, Caddy

The exit trap restarts the stopped services even if a later backup command fails. Check the command output, then check container status before resuming incoming events.

The database dump does not include PostgreSQL roles. This setup recreates its application role from the saved initialization script and .env values during recovery. PostgreSQL explains that distinction in its dump and restore guidance.

The application archive uses a temporary container, following Docker’s volume-backup approach. Do not substitute a copy of PostgreSQL’s live data directory.

Encrypt the backup bundle and keep a copy outside the server. Keep the decryption key separately available. Choose frequency and retention based on how much recent work you could afford to recreate.

Restore Into an Isolated Installation

Test recovery on a separate machine with Docker installed. Leave production DNS pointing at the original server.

Copy and decrypt a backup there. Use the saved application version and the recorded PostgreSQL version. Pull the needed images before isolating the test.

Create a fresh project directory and extract the deployment files:

mkdir -p ~/n8n-recovery
cd ~/n8n-recovery

backup_dir="/absolute/path/to/decrypted-backup"
tar -xzpf "$backup_dir/deployment.tar.gz"
chmod 600 .env

Do not generate a replacement encryption key. The restored .env must contain the original one.

Create compose.recovery.yaml:

services:
  n8n:
    environment:
      N8N_HOST: localhost
      N8N_PROTOCOL: http
      N8N_EDITOR_BASE_URL: http://localhost:5678/
      N8N_WEBHOOK_URL: http://localhost:5678/
      N8N_PROXY_HOPS: "0"
      N8N_SECURE_COOKIE: "false"

networks:
  default:
    internal: true

The internal network blocks normal outbound integration traffic. On the recovery host, also keep public application ports closed in the provider firewall.

Use this small Bash helper so every recovery command selects the separate project and the correct files. On Docker Desktop, omit sudo here and from the remaining Docker commands in this recovery section:

recovery() {
  sudo docker compose \
    -p n8n-recovery \
    -f compose.yaml \
    -f compose.recovery.yaml \
    "$@"
}

These explicit file arguments exclude the public Caddy override.

Pull the images and start only PostgreSQL:

recovery pull postgres n8n n8n-runner
sudo docker pull ubuntu:24.04
recovery up -d --wait postgres

Fresh recovery volumes are created under the n8n-recovery project. PostgreSQL’s initialization script recreates the application role.

Restore the database into this fresh recovery installation:

recovery exec -T postgres sh -c \
  'pg_restore -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
    --clean --if-exists --exit-on-error' \
  < "$backup_dir/postgres.dump"
Restore Into An Isolated Installation: Restore N8N Without Triggering Production Actions; Separate Machine And Recovery Project; Keep Production Dns Unchanged; Restore Records, Files And Original Key; Unpublish Before Starting N8N; Check Decryption

Now create the n8n container without starting the application, discover its new volume and restore the files:

recovery create n8n

recovery_container=$(recovery ps -a -q n8n)

recovery_volume=$(sudo docker inspect \
  --format '{{range .Mounts}}{{if eq .Destination "/home/node/.n8n"}}{{.Name}}{{end}}{{end}}' \
  "$recovery_container")

test -n "$recovery_volume"

sudo docker run --rm -i \
  --mount "type=volume,src=$recovery_volume,dst=/data" \
  ubuntu:24.04 \
  tar --numeric-owner -xzpf - -C /data \
  < "$backup_dir/n8n-data.tar.gz"

A restored database can contain published workflows. Before starting the application, unpublish them in the recovery copy:

recovery run --rm --no-deps n8n \
  unpublish:workflow --all

Check credential decryption without saving plaintext credential files:

recovery run --rm --no-deps n8n \
  export:credentials --all --decrypted --output=/dev/null

These are supported n8n server CLI commands. Keep the output destination as /dev/null for this check.

Start the application and runner:

recovery up -d n8n n8n-runner

Use an SSH tunnel to open the recovery instance. Confirm that you can log in and see the saved workflow.

Before permitting external connections, cancel any restored running or waiting executions and confirm that production workflows remain unpublished.

Stop the recovery stack so Docker can recreate its network:

recovery down

This keeps the named volumes. Remove the entire networks: section from compose.recovery.yaml, then restart:

recovery up -d

Now reconnect the sewing-pattern test to a test-only Google account and spreadsheet. For the local workflow, run it manually with inquiry ID TEST-RECOVERY. For the webhook version, use the test listener and its localhost Test URL through your SSH tunnel. Keep public inbound access blocked throughout.

Confirm the spreadsheet row, record the recovery commands and results, and stop the recovery installation. A backup becomes dependable when you know how to restore it.

Step 8: Keep n8n Running Reliably

Put Business Workflows Into Service

Enable real triggers after the integration and recovery checks pass. When replacing an existing instance, disable its production trigger before sending events to the replacement.

Reboot the server during a planned maintenance window:

sudo reboot

After reconnecting, check:

sudo docker compose ps
curl --fail http://127.0.0.1:5678/healthz/readiness

Confirm that PostgreSQL, n8n, the runner and Caddy returned automatically. Repeat the controlled public webhook request with a new inquiry ID.

Put Business Workflows Into Service: Check Before Retrying An N8N Action; The Write May Succeed Even When The Response Is Lost; Does The Inquiry Id Already Exist?; Yes → Prevent A Duplicate Append; No → Retry After Checking The Failure; A Failed

Use an external monitor for the public readiness address:

https://n8n.example.com/healthz/readiness

The readiness endpoint checks database connectivity and migration status. /healthz only confirms that n8n is reachable. See n8n’s health-endpoint guidance.

Monitor more than availability:

  • Workflow Failures: Configure an error workflow to send a notification when an important automation fails.
  • Backup Jobs: Alert when a backup fails or the latest successful copy becomes too old.
  • Disk Space: Watch the database, execution history and backup storage.
  • Memory: Investigate repeated container restarts or memory exhaustion.

Inspect failed executions before retrying actions that change another system. A request can succeed at the destination even if n8n never receives its response.

For the sewing-pattern workflow, check whether the inquiry ID already exists before appending a retry. Duplicate customer inquiries are annoying; duplicate actions involving money are worse.

Keep execution pruning enabled, as it is in the supplied configuration. Set retention to the history you actually need for troubleshooting, and avoid keeping sensitive request data indefinitely.

Update With a Recovery Path

Read release notes, take a fresh complete backup and test important workflows in an isolated copy before updating. That follows n8n’s update guidance.

Change N8N_VERSION in .env to the exact version you have chosen. Both n8n and the runner use that value, so their versions stay aligned.

Update With A Recovery Path: Update N8N With A Tested Recovery Path; Read Notes, Back Up And Test In Isolation; Change N8N_Version; Update N8N And Runner Together; Verify Login, Credentials, Execution And Webhook; Checks Pass → Continue Service

Apply the update:

docker compose pull n8n n8n-runner
docker compose up -d n8n n8n-runner
docker compose ps
https://www.youtube.com/watch?v=PknHkYU8Ggg

Verify login, credential access, a representative execution and the public webhook.

If the update changes the database, returning to the previous image may be insufficient. Recover using the previous application version and its matching backup when required.

Maintain Ubuntu, Docker and Caddy too. Treat a PostgreSQL major-version upgrade as its own migration, with its own backup and recovery procedure.

I would keep this work on a regular maintenance calendar. The recurring hosting bill may be smaller, but the maintenance does not disappear.

Troubleshoot Common Setup Problems

Work through problems in this order: container status, service logs, local access, proxy access, DNS and HTTPS, then the external integration.

Start with:

docker compose ps
docker compose logs --tail=100 postgres n8n n8n-runner
Troubleshoot Common Setup Problems: Troubleshoot N8N From Containers To Integrations; 1. Container Status; 2. Service Logs; 3. Local Access And Tunnel; 4. Proxy Access; 5. Dns And Https; 6. External Integration; Preserve Volumes. Remove Secrets

For the public server, also inspect:

docker compose logs --tail=100 caddy
SymptomFirst CheckSafe Corrective Action
n8n keeps restartingPostgreSQL health and n8n startup logsCorrect the database connection or file-permission problem. Preserve existing volumes while investigating.
Code node failsRunner logs, matching image versions and shared tokenAlign the versions and token, and confirm the broker address is http://n8n:5679.
Localhost will not openn8n container status and the SSH tunnelStart the missing service or reopen the tunnel. Confirm your computer’s port 5678 is available.
Public address returns 502Caddy logs and n8n service statusUse reverse_proxy n8n:5678. Inside Caddy, localhost refers to Caddy’s container.
HTTPS certificate failsA/AAAA records, ports 80/443 and Caddy logsCorrect DNS or firewall access. Remove an incorrect AAAA record.
Webhook never arrivesPublic URL, request method, authentication and published stateUse the production endpoint for a published workflow, and send the configured authentication header.
Google OAuth failsCallback URL and enabled APIsMatch the redirect URI exactly and enable both Sheets and Drive APIs. Reconnect the credential.
Workflows appear missingMounted volumes, Compose project name and database settingsLocate the original storage before creating or initializing replacement volumes.
Credentials will not decryptOriginal encryption keyRestore the matching key and application files from backup.
Schedules run at the wrong timeWorkflow timezone and instance timezoneCorrect the workflow setting or GENERIC_TIMEZONE, then verify the next scheduled run.
Password-reset email never arrivesSMTP logs and provider delivery recordsCorrect the SMTP settings and sender authorization, then recreate n8n and test again.

Remove secrets and sensitive execution data before sharing diagnostic logs. Avoid posting the full output of docker compose config, because it can include substituted passwords.

What Next?

Create the project folder and get the sewing-pattern test inquiry into your spreadsheet. Keep that small workflow as your check after restarts, restores and updates.

Once the test works, choose one real task for n8n to handle. Map what starts it, which data it needs and what should happen if an action fails before building it.

Lead Magnet Cover
FREE AI SKILL

Free AI Automation Planner

Use AI to write clear rules for when a routine should start, wait or stop.
Send My AI Automation Planner ❯
Instantly delivered to your inbox
Customer Avatar 1
Customer Avatar 2
Customer Avatar 3
Customer Avatar 4
Rated highly by 25,000+ users

Use the social buttons to share this guide when your next automation discussion reaches the server-and-backups part.

Which task would you trust to your installation first, and what would you need to verify before switching it on? Share your answer or any setup questions in the comments.

Share this post with your friends & followers:
Abhishek is a data scientist by day & an online entrepreneur by night. He is known for his ability to simplify complex concepts and make them accessible to a wider audience. He started Passive Book to share his insights and experiences on how to effectively build an online business, which has quickly become a go-to resource for anyone looking to bootstrap an online business from scratch.

Leave a Comment

Build an Online Business 
Without Quitting Your Job

Join 10,000+ solopreneurs building six-figure online businesses from scratch with limited time & tight budgets using smart systems & AI automations.
Optin Form - Main

Free Bonus: Get access to our AI workflows & cheat sheets
Person sitting with laptop in home office environment with launching rocket, coffee mug, sleeping dog, bookshelf, and house plant illustrating work-from-home online business lifestyle. Decorative image.
Thank you for sharing

Follow Us On: