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.
1. Architecture Overview
Sección titulada «1. Visión General de la Arquitectura»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 end1.1 Key Architectural Decisions
Sección titulada «1.1 Decisiones Arquitectónicas Clave»- 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, nor5678) 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.
- Main Benefit: The Ubuntu host does not expose any inbound ports (neither
- Infrastructure as Code (IaC): The infrastructure is defined declaratively through
docker-compose.ymlfiles and non-sensitive.envenvironment variables, facilitating backups and stack replication.
2. Operating System Preparation (Ubuntu)
Sección titulada «2. Preparación del Sistema Operativo (Ubuntu)»2.1 Network Configuration (Netplan)
Sección titulada «2.1 Configuración de Red (Netplan)»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:
sudo nano /etc/netplan/50-cloud-init.yamlAlign 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: 2Apply the changes:
sudo netplan apply2.2 Docker Engine Dependency Installation
Sección titulada «2.2 Instalación de Dependencias del Motor Docker»Ensure the installation of the updated engine and its official orchestration libraries:
# 1. Actualización y parche de repositorios del sistemasudo apt update && sudo apt upgrade -y
# 2. Instalación de utilidades de red y certificados segurossudo apt install -y ca-certificates curl gnupg lsb-release
# 3. Importación de las llaves GPG oficiales del registro de Dockersudo install -m 0755 -d /etc/apt/keyringscurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpgsudo chmod a+r /etc/apt/keyrings/docker.gpg
# 4. Registro del repositorio estableecho \ "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 V2sudo apt updatesudo 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:
- Access your Cloudflare Zero Trust > Networks > Tunnels portal.
- Create a new tunnel of type Cloudflared (example name:
portel-n8n-tunnel). - Copy the
TUNNEL_TOKEN(long alphanumeric text block provided by Cloudflare to authenticate your container). - 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).
- Public Domain:
4. Stack Structure and Composition (IaC)
Sección titulada «4. Estructura y Composición del Stack (IaC)»Our entire infrastructure resides in an organized manner within the ~/n8n-docker directory.
mkdir -p ~/n8n-docker && cd ~/n8n-docker4.1 Environment Variables File (.env)
Sección titulada «4.1 Archivo de Variables de Entorno (.env)»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.comN8N_PROTOCOL=httpsTIMEZONE=Europe/Madrid
# ==========================================# Credenciales de Base de Datos (PostgreSQL)# ==========================================POSTGRES_USER=portel_n8n_sec_usrPOSTGRES_PASSWORD=pg_pass_secure_demo_987654321_! # Ejemplo demostrativo y de laboratorioPOSTGRES_DB=n8n_production_db
# ==========================================# Credenciales de Seguridad (Cloudflare)# ==========================================# Sustituye este marcador por tu token obtenido en la consola de CloudflareCLOUDFLARE_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 hostvolumes: n8n_data: name: n8n_app_data pg_data: name: n8n_db_data
# Red virtual privada aisladanetworks: n8n_network: name: n8n_internal_net driver: bridge5. Console Operations and Diagnostics
Sección titulada «5. Operaciones de Consola y Diagnóstico»5.1 Initial Deployment and Stack Startup
Sección titulada «5.1 Despliegue Inicial y Arranque del Stack»To spin up the entire declared infrastructure in the background for the first time (or after making changes to the .env file):
cd ~/n8n-dockerdocker compose up -d5.2 Real-Time Log Reading
Sección titulada «5.2 Lectura de Logs en Tiempo Real»To analytically monitor the data flow or diagnose boot failures:
# Ver logs de todo el stack de serviciosdocker compose logs -f
# Diagnóstico específico del túnel de Cloudflaredocker logs -f n8n_tunnel5.3 Factory Reset (Emergency Maintenance)
Sección titulada «5.3 Restablecimiento de Fábrica (Mantenimiento de Emergencia)»[!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.
cd ~/n8n-docker# Detiene el stack eliminando los volúmenes asociadosdocker compose down -v
# Reconstruye el entorno desde cerodocker compose up -d📊 Operational Success Checklist
Sección titulada «📊 Checklist de Éxito Operativo»- ✓ 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.ymland.env) free of hardcoded secrets and integrated with graceful shutdown directives.

