Ir al contenido

Architecture Manual: Secure Deployment of n8n in Portelcore

Technical guide for the deployment of n8n using Docker Compose, persistent PostgreSQL relational database, and Zero Trust routing with Cloudflare Tunnels.

0views

This guide details the implementation of a production-oriented n8n (advanced workflow automation platform) instance. The architecture has been designed prioritizing the principles of isolation, resilience, and perimeter security.

graph TD
Client([Cliente en Internet]) -->|HTTPS / Cifrado Estricto| CFEdge[Edge de Cloudflare]
subgraph Servidor Ubuntu (Proxmox VE - Red Privada)
direction LR
CFEdge -->|Canal Seguro / Sin Puertos Abiertos| CFTunnel[Contenedor: cloudflared]
CFTunnel -->|Red Virtual Docker| n8nServer[Contenedor: n8n_server]
n8nServer -->|Persistencia Local| pgData[(Volumen: n8n_db_data)]
n8nServer -->|Conexión Segura| pgServer[Contenedor: n8n_postgres]
pgServer --> pgData
end
  • Execution Environment: Virtualized Ubuntu Server running in isolation on a Proxmox VE hypervisor.
  • Container Orchestration: Docker and Docker Compose to ensure immutable, portable, and easily auditable environments.
  • Relational Database: Migration from default storage (SQLite) to PostgreSQL 16. This decision prevents write locks under high concurrency and lays the foundation for future horizontal scalability (via Queue mode with additional workers).
  • Perimeter Security (Zero Trust): Implementation of Cloudflare Tunnels (cloudflared).
    • Main Benefit: The Ubuntu host does not expose any inbound ports (neither 80, 443, nor 5678) to the Internet. The tunnel container establishes a direct, secure, and encrypted outbound connection with the Cloudflare Edge, protecting the local network from malicious scans and delegating SSL (HTTPS) certificates to the Edge.
  • Infrastructure as Code (IaC): The infrastructure is defined declaratively through docker-compose.yml files and non-sensitive .env environment variables, facilitating backups and stack replication.

A static IP is set on the Ubuntu host to ensure transparent service resolution and avoid collisions caused by the local network DHCP server. In this high-entropy lab, the node responds at the address 172.22.40.231.

Edit the system network file:

Ventana de terminal
sudo nano /etc/netplan/50-cloud-init.yaml

Align the configuration with the corporate internal network:

network:
ethernets:
ens18:
dhcp4: no
addresses:
- 172.22.40.231/24
routes:
- to: default
via: 172.22.40.1
nameservers:
addresses:
- 1.1.1.1
- 8.8.8.8
version: 2

Apply the changes:

Ventana de terminal
sudo netplan apply

Ensure the installation of the updated engine and its official orchestration libraries:

Ventana de terminal
# 1. Actualización y parche de repositorios del sistema
sudo apt update && sudo apt upgrade -y
# 2. Instalación de utilidades de red y certificados seguros
sudo apt install -y ca-certificates curl gnupg lsb-release
# 3. Importación de las llaves GPG oficiales del registro de Docker
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
# 4. Registro del repositorio estable
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
# 5. Instalación del motor oficial y del plugin Compose V2
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
# 6. Permisos de grupo al usuario del sistema (portel_user)
sudo usermod -aG docker $USER

[!IMPORTANT] Critical Operational Step: Remember to close your active console session (exit) and log back in via SSH to refresh your user token privileges in the Docker local socket.


3. Cloudflare Zero Trust Configuration (The Tunnel)

Sección titulada «3. Configuración de Cloudflare Zero Trust (El Túnel)»

Before initializing the containers on the host, we prepare the secure tunnel in the Cloudflare console:

  1. Access your Cloudflare Zero Trust > Networks > Tunnels portal.
  2. Create a new tunnel of type Cloudflared (example name: portel-n8n-tunnel).
  3. Copy the TUNNEL_TOKEN (long alphanumeric text block provided by Cloudflare to authenticate your container).
  4. Configure the public path (Public Hostname):
    • Public Domain: n8n.portelcore.com
    • Service Type: HTTP
    • Internal URL (Destination): n8n:5678 (Note: Internal DNS resolution provided by the Docker Compose virtual network is used).

Our entire infrastructure resides in an organized manner within the ~/n8n-docker directory.

Ventana de terminal
mkdir -p ~/n8n-docker && cd ~/n8n-docker

This file centrally stores dummy listening ports, database passwords, and authentication tokens. It is strictly forbidden to upload this file with real secrets to public code control repositories.

File: ~/n8n-docker/.env

# ==========================================
# Configuración del Entorno y Dominio
# ==========================================
N8N_HOST=n8n.portelcore.com
N8N_PROTOCOL=https
TIMEZONE=Europe/Madrid
# ==========================================
# Credenciales de Base de Datos (PostgreSQL)
# ==========================================
POSTGRES_USER=portel_n8n_sec_usr
POSTGRES_PASSWORD=pg_pass_secure_demo_987654321_! # Ejemplo demostrativo y de laboratorio
POSTGRES_DB=n8n_production_db
# ==========================================
# Credenciales de Seguridad (Cloudflare)
# ==========================================
# Sustituye este marcador por tu token obtenido en la consola de Cloudflare
CLOUDFLARE_TUNNEL_TOKEN=eyJh...[TU_TOKEN_DE_TÚNEL_SEGURO_AQUÍ]...

4.2 Multi-layer Orchestration (docker-compose.yml)

Sección titulada «4.2 Orquestación Multicapa (docker-compose.yml)»

This file declares the relational database engine (Postgres 16), the n8n workflow server, and the Cloudflare tunnel agent. Advanced health checks (healthchecks) are included to mitigate service downtime and ensure clean logical dependencies.

File: ~/n8n-docker/docker-compose.yml

version: '3.8'
services:
# 1. Capa de Persistencia y Base de Datos Relacional
postgres:
image: postgres:16-alpine
container_name: n8n_postgres
restart: unless-stopped
environment:
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=${POSTGRES_DB}
volumes:
- pg_data:/var/lib/postgresql/data
networks:
- n8n_network
healthcheck:
test: ["CMD-SHELL", "pg_isready -h localhost -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
# 2. Servidor de Automatización (Lógica de Negocio)
n8n:
image: docker.n8n.io/n8nio/n8n:latest
container_name: n8n_server
restart: unless-stopped
# Nota de Seguridad: No mapeamos puertos físicos del host a internet.
# Todo tráfico es recibido localmente a través de la red de Docker por el túnel.
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}
- N8N_HOST=${N8N_HOST}
- N8N_PORT=5678
- N8N_PROTOCOL=${N8N_PROTOCOL}
- NODE_ENV=production
- WEBHOOK_URL=${N8N_PROTOCOL}://${N8N_HOST}/
- GENERIC_TIMEZONE=${TIMEZONE}
volumes:
- n8n_data:/home/node/.n8n
networks:
- n8n_network
depends_on:
postgres:
condition: service_healthy
# 3. Capa de Enlace Zero Trust (Cloudflare Tunnel)
cloudflared:
image: cloudflare/cloudflared:latest
container_name: n8n_tunnel
restart: unless-stopped
# Desactivar autoupdate evita que actualizaciones autónomas rompan la infraestructura local
command: tunnel --no-autoupdate run
environment:
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN}
networks:
- n8n_network
# Definición de volúmenes persistentes locales del host
volumes:
n8n_data:
name: n8n_app_data
pg_data:
name: n8n_db_data
# Red virtual privada aislada
networks:
n8n_network:
name: n8n_internal_net
driver: bridge

To spin up the entire declared infrastructure in the background for the first time (or after making changes to the .env file):

Ventana de terminal
cd ~/n8n-docker
docker compose up -d

To analytically monitor the data flow or diagnose boot failures:

Ventana de terminal
# Ver logs de todo el stack de servicios
docker compose logs -f
# Diagnóstico específico del túnel de Cloudflare
docker logs -f n8n_tunnel

[!CAUTION] Destructive Operation: The following command permanently deletes all containers and local host volumes (wiping credentials, users, and n8n workflow histories). Use it only in laboratories or serious contingencies.

Ventana de terminal
cd ~/n8n-docker
# Detiene el stack eliminando los volúmenes asociados
docker compose down -v
# Reconstruye el entorno desde cero
docker compose up -d

  • ✓ Strict HTTPS Encryption: End-to-end encrypted traffic natively routed via the Cloudflare Edge to n8n.portelcore.com.
  • ✓ Relational Persistence: PostgreSQL 16 database engine verified through automated health checks.
  • ✓ Isolated Network Security: Zero host ports open to the public network, channeling internal routing through a closed Docker virtual bridge.
  • ✓ Declarative Standard: IaC files (docker-compose.yml and .env) free of hardcoded secrets and integrated with graceful shutdown directives.