October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Self-Host n8n and a Node.js API Locally with Docker Compose

Run n8n and a small Node.js API locally with Docker Compose, preserve workflow data in a named volume, and call the private API from an n8n workflow.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run n8n and a small Node.js API as separate services in one Docker Compose project. In this local-development example, you open n8n in your browser, keep the API private to the Compose network, and have workflows call it by its service name. A named volume preserves n8n’s workflows and settings across container restarts; no public domain is needed for local testing.

What this local stack does

Docker Compose starts and connects the services. n8n coordinates your workflows, while the Node.js service supplies a small custom HTTP endpoint for behavior your workflow needs. Here, requests go from n8n to the API—not the other way around.

As an Amazon Associate I earn from qualifying purchases.

The example exposes n8n on your host at http://localhost:5678. The API listens on port 3000 inside its container but has no host port mapping, so it is reachable by n8n on the shared Compose network, not directly from your computer or the public internet. Docker’s Compose networking documentation explains service-to-service communication and service-name DNS.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prerequisites and project files

Install Docker Engine and Docker Compose v2. n8n documents Compose as an option when you want control over configuration or want to add n8n to an existing Compose project. Its recommendation of 4 GB RAM and 2 vCPUs applies to the sandbox stack in its guide, not as a universal minimum for this simpler local setup.

#1 Best Overall
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
  • Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM)
  • Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
  • CanaKit Turbine Black Case for the Raspberry Pi 5
  • CanaKit Low Noise Bearing System Fan
  • Mega Heat Sink - Black Anodized

Create a project directory with these files:

local-automation/
├── compose.yaml
├── .env
├── .gitignore
└── api/
    ├── Dockerfile
    └── server.js

Use the following configuration as a local-development starting point. Change the timezone to an IANA timezone appropriate for your location. Keep .env out of version control.

compose.yaml

services:
  n8n:
    image: docker.n8n.io/n8nio/n8n:latest
    ports:
      - "127.0.0.1:5678:5678"
    environment:
      TZ: ${GENERIC_TIMEZONE}
      GENERIC_TIMEZONE: ${GENERIC_TIMEZONE}
      N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY}
      N8N_BLOCK_ENV_ACCESS_IN_NODE: "true"
      N8N_RESTRICT_FILE_ACCESS_TO: /home/node/.n8n
    volumes:
      - n8n_data:/home/node/.n8n
    depends_on:
      - api
    restart: unless-stopped

  api:
    build: ./api
    environment:
      API_TOKEN: ${API_TOKEN}
    expose:
      - "3000"
    restart: unless-stopped

volumes:
  n8n_data:

The loopback host binding limits n8n’s published port to this computer. The API’s expose declaration documents its container port; it does not publish that port to the host. The Compose service name api is the hostname n8n will use. Inside a container, localhost refers to that same container, not a different service.

Rank #2
CanaKit Raspberry Pi 5 16GB Starter Kit PRO - Turbine Black (128GB Edition) (16GB RAM)
  • Includes Raspberry Pi 5 16GB with 2.4Ghz 64-bit quad-core CPU (16GB RAM)
  • Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
  • CanaKit Turbine Black Case for the Raspberry Pi 5
  • CanaKit Low Noise Bearing System Fan
  • Mega Heat Sink - Black Anodized

.env

GENERIC_TIMEZONE=America/New_York
N8N_ENCRYPTION_KEY=replace-with-a-long-random-secret
API_TOKEN=replace-with-another-long-random-secret

Replace both example secrets with unique, high-entropy values before starting. Keep a protected copy of the encryption key: n8n needs it to decrypt saved credentials. Do not commit .env or share its contents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

.gitignore

.env
local-files/

Create the Node.js API

Node.js’s standard node:http module can create an HTTP server. This implementation adds a single authenticated POST /api/echo route, limits the request body, checks JSON and required fields, and returns explicit errors. It binds to 0.0.0.0 so the other container can reach it.

Rank #3
CanaKit Raspberry Pi 5 Essentials Starter Kit (4GB RAM)
  • CanaKit Raspberry Pi 5 Essentials Starter Kit

api/Dockerfile

FROM node:22-alpine
WORKDIR /app
COPY server.js ./server.js
USER node
EXPOSE 3000
CMD ["node", "server.js"]

api/server.js

const http = require('node:http');

const token = process.env.API_TOKEN;
if (!token) {
  throw new Error('API_TOKEN must be set');
}

const maxBodyBytes = 16 * 1024;

function send(res, status, payload) {
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
  res.end(JSON.stringify(payload));
}

const server = http.createServer((req, res) => {
  if (req.method !== 'POST' || req.url !== '/api/echo') {
    return send(res, 404, { error: 'Not found' });
  }

  if (req.headers.authorization !== `Bearer ${token}`) {
    return send(res, 401, { error: 'Unauthorized' });
  }

  if (!req.headers['content-type']?.includes('application/json')) {
    return send(res, 415, { error: 'Expected application/json' });
  }

  let body = '';
  let tooLarge = false;
  req.on('data', chunk => {
    body += chunk;
    if (Buffer.byteLength(body) > maxBodyBytes) {
      tooLarge = true;
      send(res, 413, { error: 'Request body too large' });
      req.destroy();
    }
  });

  req.on('end', () => {
    if (tooLarge) return;
    let data;
    try {
      data = JSON.parse(body);
    } catch {
      return send(res, 400, { error: 'Invalid JSON' });
    }
    if (!data || typeof data.message !== 'string' || !data.message.trim()) {
      return send(res, 422, { error: 'message must be a non-empty string' });
    }
    return send(res, 200, { received: data.message });
  });
});

server.listen(3000, '0.0.0.0');

This deliberately small API is an example, not a complete production service. Add appropriate authorization, validation, rate limits, logging, and error handling before adapting it for sensitive or public operations. Node’s HTTP layer handles HTTP parsing and streaming; application routing and validation are your responsibility.

Start the services and call the API from n8n

  1. From the project directory, start the stack with docker compose up -d --build.
  2. Open http://localhost:5678 and complete n8n’s initial setup.
  3. Create a workflow with an HTTP Request node. Set method to POST, URL to http://api:3000/api/echo, and body content type to JSON. Send a body such as {"message":"hello from n8n"}.
  4. Add an Authorization header with value Bearer followed by the exact API_TOKEN from .env. Store the token in n8n credentials rather than hard-coding it in a workflow that will be shared or exported.
  5. Execute the workflow. A valid request returns HTTP 200 and JSON containing received. Missing or invalid authentication returns 401; malformed JSON returns 400; missing or blank message returns 422; a non-JSON content type returns 415.

To inspect startup output, run docker compose logs -f n8n api. If the API cannot be reached, check that both containers are running and that the URL uses api, not localhost. Confirm the API process listens on 0.0.0.0:3000.

Rank #4
SANOOV Raspberry Pi 5 4GB Kit, 4GB RAM Single Board Computer with Active Cooler and ABS Case, Complete Raspberry Pi 5 Starter Kit for IoT Robotics Retro Gaming
  • All-in-One Complete Kit: This SANOOV RPi 5 bundle comes with Raspberry Pi 5 4GB RAM single board, active cooler, durable ABS case and screwdriver. No extra parts needed, ready to use right out of the box for beginners and hobbyists
  • Powerful Single Board Computer: Equipped with 4GB RAM and high-performance processor, delivers fast running speed for 4K playback, AI projects, programming and daily computing tasks. SANOOV for raspberry pi 5 4GB is equipped with broadcom 64 quad-core Arm Cortex A76 processor with gigabit ethernet and upgraded with IEEE 802.11ac Wi-Fi, Bluetooth 5.0 dual-band 2.4Ghz and 5Ghz and Power Over Ethernet (POE). Upgrading delivers 2-3 x speed vs Pi 4, redefining the experience
  • Efficient Active Cooler: Effectively lowers operating temperature and prevents performance throttling. Runs quietly even under long-time heavy load, ensures stable operation all day long. SANOOV RPi 5 4GB kit offer an active cooler, which combines an aluminium heatsink with a high-performance PWM fan. Active cooler is fully compatible with the Pi OS, which can effectively reduce the temperature of RPi5 and ensure its good performance during long-term high load operation
  • Sturdy ABS Protective Case: Well-fitted for Raspberry Pi 5 board, can be secured with 4 screws to effectively protect the Pi 5 motherboard from damage, reserves full access to all ports and buttons. SANOOV uses ABS material to produce the case, which has a softer texture and feel. Meanwhile, SANOOV case adopts a layered design for easy disassembly and installation. (Tip: The Case cannot install M.2 HAT Add on Board and Solid State Drive!)
  • Wide Application & Full Compatibility: Seamlessly compatible with official OS and mainstream peripheral accessories for Raspberry Pi 5. Whether you are a beginner, student, electronics hobbyist or professional developer, this all-in-one kit meets your diverse needs. It excels in IoT projects, robotics design, retro gaming devices, home media servers and other DIY creations. Backed by a large global community, you can easily find guides, technical support and shared projects online
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep workflows and settings after restarts

The named volume n8n_data stores n8n’s /home/node/.n8n directory, the documented location for persistent instance data. Restarting or recreating containers with docker compose down does not remove this named volume. Avoid docker compose down -v unless you intend to delete it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Back up the n8n volume and the encryption key together, and keep backups somewhere protected outside the running container. A recovery plan should restore both the saved data and the matching key; losing the key can make stored credentials unusable. If workflows need to read or write host files, add a separate bind mount such as ./local-files:/files and restrict what you share. n8n’s Docker Compose guide uses that separate mount for shared files.

Best Value
RasTech Raspberry Pi 5 8GB Kit with Active Cooler and Pi5 Case
  • 【What you Get】You will get 1*Pi 5 8GB Single Board,1*RasTech Case,1*Active Cooler,1*Screwdriver,1*Installation instructions,12-month free warranty, lifetime service, 24-hour prompt and friendly response.
  • 【More Connectors】There are two USB 3.0 ports(5Gbps simultaneously) and two USB 2.0 ports, which triple total bandwidth ,support any combination of up to two cameras or displays. Peak SD card performance is doubled through support for the SDR104 high-speed mode. It provides a smooth desktop experience for you. Offer Gigabit Ethernet and a PCIe interface, along with dual-band Wi-Fi and Bluetooth 5.0/BLE wireless capability. The RasTech Pi 5 Kit use the new 27W 5.1V 5A USB-C power connector.
  • 【 Support Dual 4Kp60 Display 】Each of the two microHDMI sockets can control a 4K display at 60 Hertz, now support HDR, offering super HD video for media streaming projects. RPi 5 is the first RPi model that comes with a PCI Express port (PCIe 2.0 x1 with 500 MB/s) to attach SSDs (requires separate M.2 HAT).
  • 【 Excellent Chips And Applications】Pi 5 is a full-size Pi computer using silicon built in-house at Pi. The RP1 “southbridge” provides the bulk of the I/O capabilities for Pi 5. Pi 5 is more friendly and convenient in the development of Internet of Things, Web development, machine identification, automatic control and other electronic equipment applications and network.
  • 【 Faster CPU, Better GPU 】 Pi 5 features a Broadcom BCM2712 64-bit quad-core Arm Cortex-A76 processor running at 2.4GHz, it delivers a 2–3× increase in CPU performance relative to RaspberryPi 4. The 800MHz VideoCore VII GPU is compatible to OpenGL ES 3.1 and Vulkan 1.2, substantial uplift in graphics performance. Pi 5 Offers lightning-fast CPU speed, a PCI Express interface, a Real Time Clock (RTC) and a power button and runs significantly cooler than Pi 4.

Configure secrets and restrict access

The Compose .env file supplies values to the Compose configuration; it is not automatically a secure secret store. Protect it with filesystem permissions, exclude it from source control, and use your deployment platform’s secret mechanism for shared or production deployments. n8n supports _FILE variants for selected settings, allowing supported variables to load from files; verify support for each variable you use in the environment-variable reference.

This example sets N8N_BLOCK_ENV_ACCESS_IN_NODE to limit access to environment variables from Code nodes and expressions, and N8N_RESTRICT_FILE_ACCESS_TO to narrow file access to n8n’s data directory. Adjust these controls only when a workflow genuinely requires broader access. They do not replace authentication, network restrictions, careful secret handling, or updates. Run n8n’s built-in security audit to check for common self-hosted configuration issues; see the security audit documentation.

Local testing versus public webhooks

Access mode Host exposure Public URL and TLS Operational responsibility
Local development in this example n8n is bound to host loopback; API has no host port mapping. No public domain or TLS setup is needed to open n8n locally. Protect local credentials and persistent data; keep services updated.
External webhook deployment Expose n8n through a deliberate public ingress; do not publish the API unless required. Use a public URL, reverse proxy, and TLS, and configure n8n’s webhook URL and host/protocol settings for that deployment. You are responsible for firewall rules, authentication, updates, secret storage, and secure proxy configuration.

A local-only stack cannot receive webhooks from services on the public internet. Treat external webhook access as a separate deployment: configure a reachable public URL and reverse proxy with TLS, apply firewall and authentication controls, and follow n8n’s Compose deployment guidance for settings such as WEBHOOK_URL. Do not apply public-facing settings blindly to local testing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

Bestseller No. 1
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM); CanaKit Turbine Black Case for the Raspberry Pi 5
$259.95
Bestseller No. 2
CanaKit Raspberry Pi 5 16GB Starter Kit PRO - Turbine Black (128GB Edition) (16GB RAM)
CanaKit Raspberry Pi 5 16GB Starter Kit PRO - Turbine Black (128GB Edition) (16GB RAM)
Includes Raspberry Pi 5 16GB with 2.4Ghz 64-bit quad-core CPU (16GB RAM); CanaKit Turbine Black Case for the Raspberry Pi 5
$419.99
Bestseller No. 3
CanaKit Raspberry Pi 5 Essentials Starter Kit (4GB RAM)
CanaKit Raspberry Pi 5 Essentials Starter Kit (4GB RAM)
CanaKit Raspberry Pi 5 Essentials Starter Kit
$189.99

Stop, restart, and update the stack

  • Stop and remove containers while preserving named data: docker compose down.
  • Start existing services again: docker compose up -d.
  • Rebuild the API after changing its source or Dockerfile: docker compose up -d --build api.
  • Choose and pin an n8n image version for repeatable deployments rather than relying indefinitely on latest; review release notes and back up before upgrading.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.