AWS · EC2 · Docker · n8n · SSH · localhost
Install n8n on AWS EC2 and access localhost through an SSH tunnel
n8n runs on AWS, while you open its editor at http://localhost:15678 on your computer. An SSH tunnel carries the connection to the private EC2 port: no domain, Nginx, certificate or public port 5678 is required.
Local describes browser access, not execution: workflows, files, credentials and outgoing HTTP requests remain on EC2. Closing the tunnel stops neither n8n nor AWS billing.
1. What the SSH tunnel connects
http://localhost:15678127.0.0.1:15678ssh -L127.0.0.1:5678Docker → n8n → PostgreSQLThe first 127.0.0.1 belongs to your computer; the destination 127.0.0.1 is interpreted from EC2. Docker publishes n8n only on the server loopback. PostgreSQL and the runner broker publish no host ports. SSH forwards bytes, not HTTP proxy headers: this setup does not set N8N_PROXY_HOPS.
2. Prepare EC2 and your key
Launch Ubuntu Server 24.04 LTS x86_64, for example a t3.medium with 4 GB RAM and 20–30 GB gp3 storage for these three containers. This is a starting point, not a universal requirement: measure actual usage. The instance needs a public IPv4 and outbound internet access for packages and container images. Wait for EC2 status checks to pass.
Download your key pair and keep it on your computer as ~/.ssh/n8n-key.pem. Replace EC2_PUBLIC_IP with the EC2 public IPv4. Verify the host fingerprint against a trusted AWS source before accepting the first connection; do not disable StrictHostKeyChecking. Never copy the private key to EC2.
Run on your computer · Bash
# LOCAL: macOS / Linux / WSL (the private key stays on this computer).
chmod 400 ~/.ssh/n8n-key.pem
ssh -i ~/.ssh/n8n-key.pem ubuntu@EC2_PUBLIC_IPOn Windows you can use WSL or Git Bash for the Bash blocks. With PowerShell use OpenSSH and a Windows key path; follow the AWS key-permission guide if it reports “bad permissions”. chmod is not a native PowerShell command.
3. Install Docker on EC2
Connect using SSH, update Ubuntu and install Docker from its official repository. After adding your user to the docker group, log out and reconnect before continuing. This group grants root-equivalent access: use it only for administrators.
Run in the EC2 terminal
# EC2 terminal only
sudo apt update && sudo apt upgrade -y
sudo timedatectl set-timezone Europe/Madrid
free -h
# If the update asks for a reboot, reboot and reconnect before continuing.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
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] \
https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
| sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
# Allow Docker access; log out and reconnect before the next commands.
sudo usermod -aG docker $USER
docker --version
docker compose version4. Create the private project and secrets
Use ~/n8n-ssh and the Compose project name n8n-ssh to keep this separate from the public tutorial. Generate three different secrets and paste them into .env. In Nano save with Ctrl+O and Enter, then exit with Ctrl+X. Do not share .env or the encryption key.
Run in the EC2 terminal
mkdir -p ~/n8n-ssh/local-files ~/n8n-ssh/backups
cd ~/n8n-ssh
sudo chown 1000:1000 local-files
umask 077
# Generate three DIFFERENT secrets. Keep an encrypted copy off this server.
openssl rand -hex 32 # N8N_ENCRYPTION_KEY
openssl rand -hex 24 # POSTGRES_PASSWORD
openssl rand -hex 32 # N8N_RUNNERS_AUTH_TOKEN
nano .env# ~/n8n-ssh/.env - replace ALL placeholders; do not commit this file.
N8N_VERSION=2.44.7
N8N_HOST=localhost
POSTGRES_PASSWORD=REPLACE_WITH_RANDOM_PASSWORD
N8N_ENCRYPTION_KEY=REPLACE_WITH_RANDOM_ENCRYPTION_KEY
N8N_RUNNERS_AUTH_TOKEN=REPLACE_WITH_RANDOM_RUNNER_TOKEN5. Compose: n8n, PostgreSQL and a runner
Save the following as ~/n8n-ssh/docker-compose.yml. n8n and runners share the exact version set in .env. Persistent volumes retain the database and configuration when containers are recreated.
name: n8n-ssh
services:
postgres:
image: postgres:16
restart: unless-stopped
environment:
POSTGRES_USER: n8n
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
POSTGRES_DB: n8n
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U n8n -d n8n"]
interval: 10s
timeout: 5s
retries: 10
n8n:
image: docker.n8n.io/n8nio/n8n:${N8N_VERSION:?Set N8N_VERSION}
restart: unless-stopped
ports:
- "127.0.0.1:5678:5678"
environment:
DB_TYPE: postgresdb
DB_POSTGRESDB_HOST: postgres
DB_POSTGRESDB_DATABASE: n8n
DB_POSTGRESDB_USER: n8n
DB_POSTGRESDB_PASSWORD: ${POSTGRES_PASSWORD}
N8N_HOST: ${N8N_HOST:?Set N8N_HOST}
N8N_PORT: 5678
N8N_PROTOCOL: http
N8N_WEBHOOK_URL: http://localhost:15678/
N8N_EDITOR_BASE_URL: http://localhost:15678/
N8N_SECURE_COOKIE: "false"
N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY:?Set N8N_ENCRYPTION_KEY}
GENERIC_TIMEZONE: Europe/Madrid
TZ: Europe/Madrid
N8N_RUNNERS_MODE: external
N8N_RUNNERS_BROKER_LISTEN_ADDRESS: 0.0.0.0
N8N_RUNNERS_AUTH_TOKEN: ${N8N_RUNNERS_AUTH_TOKEN:?Set runner token}
N8N_RESTRICT_FILE_ACCESS_TO: /files
N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS: "true"
N8N_DIAGNOSTICS_ENABLED: "false"
EXECUTIONS_DATA_PRUNE: "true"
EXECUTIONS_DATA_MAX_AGE: 168
EXECUTIONS_DATA_PRUNE_MAX_COUNT: 10000
volumes:
- n8n_data:/home/node/.n8n
- ./local-files:/files
depends_on:
postgres:
condition: service_healthy
task-runners:
image: n8nio/runners:${N8N_VERSION:?Set N8N_VERSION}
restart: unless-stopped
environment:
N8N_RUNNERS_TASK_BROKER_URI: http://n8n:5679
N8N_RUNNERS_AUTH_TOKEN: ${N8N_RUNNERS_AUTH_TOKEN}
depends_on:
- n8n
volumes:
postgres_data:
n8n_data:6. Start and verify on EC2
Create the Compose file in Nano, validate without printing secrets, then start the services. Wait for PostgreSQL to be healthy and n8n and task-runners to be running. If healthz initially fails, inspect the logs and repeat the check once startup completes.
Run in the EC2 terminal
cd ~/n8n-ssh
chmod 600 .env
nano docker-compose.yml
# Validate without printing the resolved secrets.
docker compose config --quiet
docker compose pull
docker compose up -d
docker compose ps
docker compose logs --tail 80 n8n task-runners
curl -fsS http://127.0.0.1:5678/healthz# EC2 terminal
cd ~/n8n-ssh
docker compose ps
curl -fsS http://127.0.0.1:5678/healthz
sudo ss -ltnp | grep ':5678'
# Published listener must be 127.0.0.1:5678, not 0.0.0.0:5678 or [::]:5678.7. Open the tunnel from your computer
Open another terminal on your computer. Do not run this command inside EC2. Leave this terminal open: no output is normal. The local listener is accessible only from your computer, not from other devices on your LAN.
Run on your computer · macOS / Linux / WSL
# LOCAL: keep this terminal open; no output is normal.
ssh -N -T -i ~/.ssh/n8n-key.pem \
-o IdentitiesOnly=yes -o ExitOnForwardFailure=yes \
-o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
-L 127.0.0.1:15678:127.0.0.1:5678 ubuntu@EC2_PUBLIC_IP-L defines local forwarding; -N skips the remote shell; -T skips a pseudo-terminal. ExitOnForwardFailure catches listener setup failures such as an occupied port; it does not guarantee n8n is ready. Keepalives help detect a dead connection but do not reconnect automatically.
Single-line PowerShell alternative
ssh -N -T -i "C:\Users\YOUR_USER\.ssh\n8n-key.pem" -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 127.0.0.1:15678:127.0.0.1:5678 ubuntu@EC2_PUBLIC_IP8. Open the editor and create your account
With the tunnel running, open exactly http://localhost:15678. Create the owner account with a strong password and retain the project encryption key. SSH provides network access; it does not replace n8n login. Use the same hostname, localhost, consistently to avoid separate sessions for localhost and 127.0.0.1.
http://localhost:15678
9. Check that access remains private
In a second local terminal, healthz should respond. EC2_PUBLIC_IP:5678 must fail; a failed request alone does not prove isolation, so also inspect the security group and remote listener. Do not open 5678 to fix a tunnel issue.
Run on your computer
# LOCAL: a second terminal, with the SSH tunnel still running
curl -fsS http://localhost:15678/healthz
# In PowerShell use: curl.exe -fsS http://localhost:15678/healthz
# This request must FAIL (5678 stays closed in the EC2 security group):
curl --connect-timeout 5 http://EC2_PUBLIC_IP:567810. New example: a shopping budget
Webhook → Calculate budget → Return budget
Import the lab JSON. It connects Webhook → Calculate budget (Code, JavaScript, Run Once for All Items) → Return budget. No third-party credentials are needed. It sums products in cents, adds shipping, then applies your chosen VAT percentage to products plus shipping. This is a teaching calculation, not an invoice generator.
Download the budget workflow JSON
For the first test, open the workflow, click Listen for test event or Execute workflow, then send a request from a second LOCAL terminal. /webhook-test/ listens only during a test. Save and publish the workflow to call /webhook/presupuesto repeatedly, always from a client that can reach the tunnel.
Run on your computer · Bash
# LOCAL: click Listen for test event / Execute workflow in n8n first.
curl -i http://localhost:15678/webhook-test/presupuesto \
-H 'Content-Type: application/json' \
-d '{"items":[{"name":"Monitor","quantity":2,"unitPrice":150},{"name":"Keyboard","quantity":1,"unitPrice":25}],"shipping":5,"vatPercent":21}'
# After Save + Publish, use /webhook/presupuesto for repeated calls.Equivalent PowerShell test
# LOCAL PowerShell: write the body to a file to avoid native argument quoting issues.
'{"items":[{"name":"Monitor","quantity":2,"unitPrice":150},{"name":"Keyboard","quantity":1,"unitPrice":25}],"shipping":5,"vatPercent":21}' | Set-Content -Encoding ascii budget.json
curl.exe -i http://localhost:15678/webhook-test/presupuesto -H "Content-Type: application/json" --data-binary "@budget.json"Expected result · HTTP 200
{"ok":true,"currency":"EUR","subtotal":325,"shipping":5,"vatPercent":21,"vat":69.3,"total":399.3}Two monitors at 150 and one keyboard at 25 total 325; shipping adds 5, 21% of 330 is 69.30, and the total is EUR 399.30. JSON field names remain in English in both language versions to keep one API contract.
Data validation · HTTP 400
The code rejects empty lists or more than 50 items, non-integer quantities outside 1–1000, non-finite/non-numeric prices and negative amounts. unitPrice allows up to 1,000,000, shipping up to 10,000, and vatPercent from 0 to 100. JSON decimals use a dot. Each unit price is rounded to cents before multiplication.
# LOCAL: after publishing, test validation without entering the editor.
curl -i http://localhost:15678/webhook/presupuesto \
-H 'Content-Type: application/json' \
-d '{"items":[{"name":"Monitor","quantity":-1,"unitPrice":150}]}'
# Expected: HTTP 400 with ok:false.Show the Calculate budget node code
const body = $input.first().json.body;
const fail = (error) => [{ json: { ok: false, error } }];
if (!body || !Array.isArray(body.items) || body.items.length < 1 || body.items.length > 50) {
return fail('Send between 1 and 50 items');
}
let subtotalCents = 0;
for (const item of body.items) {
if (typeof item?.name !== 'string' || !item.name.trim() ||
!Number.isInteger(item.quantity) || item.quantity < 1 || item.quantity > 1000 ||
typeof item.unitPrice !== 'number' || !Number.isFinite(item.unitPrice) ||
item.unitPrice < 0 || item.unitPrice > 1000000) {
return fail('Each item needs a name, quantity 1..1000 and unitPrice 0..1000000');
}
// Round each unit price to cents before multiplying, avoiding 0.1 + 0.2 errors.
const unitCents = Math.round((item.unitPrice + Number.EPSILON) * 100);
subtotalCents += unitCents * item.quantity;
}
const shipping = body.shipping ?? 0;
const vatPercent = body.vatPercent ?? 21;
if (typeof shipping !== 'number' || !Number.isFinite(shipping) || shipping < 0 || shipping > 10000 ||
typeof vatPercent !== 'number' || !Number.isFinite(vatPercent) || vatPercent < 0 || vatPercent > 100) {
return fail('shipping must be 0..10000 and vatPercent 0..100');
}
const shippingCents = Math.round((shipping + Number.EPSILON) * 100);
const vatCents = Math.round((subtotalCents + shippingCents) * vatPercent / 100);
return [{ json: {
ok: true, currency: 'EUR', subtotal: subtotalCents / 100,
shipping: shippingCents / 100, vatPercent, vat: vatCents / 100,
total: (subtotalCents + shippingCents + vatCents) / 100,
} }];11. What works without a public URL
Manual workflows, published schedules while EC2 and n8n stay running, outbound HTTP requests and sending Telegram messages work. Sending messages requires a bot credential and a destination, but no incoming webhook.
Telegram Trigger, Stripe and other providers cannot reach your localhost:15678: that name refers to the calling machine. A -L tunnel creates neither a public URL nor a reverse tunnel. For these triggers use a public HTTPS endpoint as in the other tutorial. This lab webhook works from your computer through the SSH tunnel.
Some OAuth providers allow localhost callbacks; others require a registered HTTPS URL. Check the provider policy and use the callback URL n8n displays rather than assuming every credential will work with this setup.
12. Save the tunnel in ~/.ssh/config
Add this block to your local config file, preserving existing entries, and replace the IP and key path. Use the short command instead of the long command: running both at once would compete for local port 15678.
Run on your computer
# LOCAL: ~/.ssh/config (Windows OpenSSH: %USERPROFILE%\.ssh\config)
Host n8n-ec2-lab
HostName EC2_PUBLIC_IP
User ubuntu
IdentityFile ~/.ssh/n8n-key.pem
IdentitiesOnly yes
ForwardAgent no
LocalForward 127.0.0.1:15678 127.0.0.1:5678
ExitOnForwardFailure yes
ServerAliveInterval 30
ServerAliveCountMax 3# LOCAL: after saving the Host entry above
ssh -N -T n8n-ec2-lab13. Backups, updates and stopping
Create backup.sh from the script below. It briefly stops n8n and its runner to capture PostgreSQL, .env, Compose, the .n8n volume and local files consistently. Schedule a maintenance window and copy every complete directory to encrypted storage outside EC2. A backup on the same EBS volume is lost if that volume is deleted.
Run in the EC2 terminal
cd ~/n8n-ssh
nano backup.sh
# Paste the script below, save, then:
chmod 700 backup.sh
./backup.sh
crontab -e
# Add this line (Ubuntu login user):
# 30 3 * * * /home/ubuntu/n8n-ssh/backup.sh >> /home/ubuntu/n8n-ssh/backups/cron.log 2>&1Show the complete backup script
#!/usr/bin/env bash
set -euo pipefail
umask 077
cd "$HOME/n8n-ssh"
mkdir -p backups
exec 9>backups/.backup.lock
flock -n 9 || exit 0
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
DEST="backups/$STAMP"
mkdir "$DEST"
# Stop writers so the database and files belong to the same recovery point.
trap 'docker compose up -d n8n task-runners >/dev/null' EXIT
docker compose stop n8n task-runners
docker compose exec -T postgres pg_dump -U n8n -d n8n -Fc > "$DEST/database.dump"
cp .env docker-compose.yml "$DEST/"
docker compose run --rm -T --no-deps --user 0 --entrypoint sh n8n \
-c 'tar -C /home/node/.n8n -czf - .' > "$DEST/n8n-data.tar.gz"
tar -czf "$DEST/local-files.tar.gz" local-files
test -s "$DEST/database.dump"
(cd "$DEST" && sha256sum .env docker-compose.yml database.dump n8n-data.tar.gz local-files.tar.gz > SHA256SUMS)
echo "Backup ready: $DEST"
# Copy this directory to encrypted storage on ANOTHER machine.
# Add retention only after verifying off-server copies and a restore.Recover on an empty instance using the same pinned version and all files from one backup. The other tutorial contains pg_restore and volume recovery instructions: adapt the folder to ~/n8n-ssh and use THIS backup’s Compose file. During a recovery drill isolate restored workflows to prevent external actions. Do not downgrade n8n against a migrated database without restoring the pre-upgrade backup. Public installation with Nginx, HTTPS and Telegram.
cd ~/n8n-ssh
./backup.sh
# Read release notes; edit N8N_VERSION to the chosen stable release.
# Keep n8n and runners on the SAME version. Keep PostgreSQL on major 16.
nano .env
docker compose config --quiet
docker compose pull
docker compose up -d
docker compose ps
docker compose logs --tail 80 n8n task-runners
curl -fsS http://127.0.0.1:5678/healthz
# Test login, an existing credential, and one production webhook.
# Keep old images and the pre-upgrade backup until verification finishes.Ctrl+C in the tunnel terminal closes only browser access. Scheduled workflows remain on AWS. Stop n8n from the remote terminal, or stop EC2 in the AWS console. EBS storage and public IPv4 addresses may still incur charges while an instance is stopped. Without an Elastic IP, the public IPv4 can change after stop/start: update the tunnel command or SSH alias.
# LOCAL: Ctrl+C in the foreground SSH tunnel terminal closes the tunnel.
# EC2: these commands affect the remote application, not your laptop.
cd ~/n8n-ssh
docker compose stop n8n task-runners
# Start again when needed:
docker compose up -d
# Do not use "docker compose down -v": it deletes the persistent volumes.14. Troubleshooting
| Symptom | What to check |
|---|---|
| SSH timeout | Check the EC2 public IP, status checks, subnet internet route, TCP 22 security-group rule for your current IP, and any host firewall. |
| Permission denied (publickey) | Use ubuntu for the Ubuntu AMI, the matching key and restrictive private-key permissions. |
| Address already in use | Close an older tunnel or use another local port. Update both n8n URL settings if the port changes. |
| channel open failed / Connection refused | The SSH connection may be fine, but n8n is not reachable at EC2 loopback:5678. Check docker compose ps, logs and remote healthz. |
| Cookie / login loop | Use the documented localhost URL and HTTP-only private lab setting; recreate n8n after editing environment variables and clear only this local site’s cookies if needed. |
| Webhook 404 | Start the test listener for /webhook-test/, or publish the workflow for /webhook/. Check the presupuesto path and HTTP POST method. |
| Tunnel disconnects | Reconnect SSH. Keepalives detect a dead connection; they do not restart it. Check sleep, VPN and public-IP changes. |
| Telegram Trigger fails | It needs a public HTTPS webhook. Sending Telegram messages and receiving webhook-triggered messages are different operations. |
Project files
Save compose.yaml as docker-compose.yml and n8n-ssh.env.example as .env in ~/n8n-ssh. Replace all example secrets. The workflow JSON is unpublished and contains no credentials.
Official sources and verification scope
Calculation snippets and file structure are checked automatically, along with shell syntax and tunnel configuration. Provisioning a new EC2, importing the workflow into n8n and testing the full connection require your own instance and key. No AWS screenshots or executions are presented as evidence of runs that did not occur.