A comprehensive Docker Compose stack for running N8N workflow automation with integrated AI services, auto-scaling, and monitoring capabilities.
Latest Update: Now includes Cloudflare tunnel support, refactored auto-scaling, and comprehensive AI service integration.
This platform combines N8N workflow automation with a suite of AI services, providing a complete automation and AI processing solution:
- N8N Workflow Engine - Main automation platform with queue-based processing
- Dynamic Auto-Scaling - Intelligent worker scaling based on queue metrics
- AI Services - Video generation, text-to-speech, image processing, and more
- Real-time Monitoring - Queue metrics and system observability
- Reverse Proxy - Traefik with SSL termination and routing
- Data Persistence - PostgreSQL database and Redis queue management
π‘ Open the live, animated diagram β β data particles flow between services, hover any service for details, scroll to zoom and drag to pan. GitHub renders the static SVG above (it strips SVG animation inline); open
architecture.htmlvia GitHub Pages or download it to see the motion. The standalonearchitecture.animated.svgalso animates when opened directly.Source:
architecture.mmdβ regenerate everything withdocs/diagrams/render.sh.
- π Dynamic Auto-Scaling - Intelligent worker scaling based on queue depth
- π€ Integrated AI Services - Video generation, image processing, TTS, and more
- π Real-time Monitoring - Queue metrics with structured logging
- π Security First - Cloudflare tunnels, non-root containers, encrypted data
- π Production Ready - Health checks, backups, and graceful shutdowns
- π¦ Easy Deployment - Single Docker Compose command
- π₯οΈ CPU Processing - All AI services run on CPU (GPU support planned for future versions)
- π§ Highly Configurable - Environment-based configuration
- Docker & Docker Compose v2+ - Container orchestration
- System Requirements:
- 16GB RAM minimum (32GB+ recommended for AI services)
- 100GB+ free disk space
- Linux host (tested on Ubuntu/Fedora)
- Note: Current version runs on CPU only (GPU acceleration coming in future versions)
- Cloudflare Account - For secure tunneling (recommended)
# Clone the repository
git clone https://github.com/askb/ai-n8domata.git
cd ai-n8domata
# Initialize submodules for AI services
git submodule update --init --recursive
# Create Docker network (for external integrations)
docker network create shark# Copy the example environment file
cp .env.example .env
# Edit configuration (IMPORTANT: Set your own passwords!)
nano .envπ Critical Environment Variables to Configure:
# Cloudflare Tunnel (get from cloudflare.com)
CLOUDFLARE_TUNNEL_TOKEN=your-tunnel-token-here
# Security (GENERATE NEW VALUES!)
N8N_ENCRYPTION_KEY=your-32-character-encryption-key
POSTGRES_PASSWORD=your-secure-database-password
# Domains (configure your subdomains)
N8N_HOST=n8n.yourdomain.com
N8N_WEBHOOK=webhook.yourdomain.com
TRAEFIK_HOST=traefik.yourdomain.com
# AI Service APIs (optional but recommended)
PEXELS_API_KEY=your-pexels-api-key
OPENAI_API_KEY=your-openai-api-keyOption A: Core Services Only (Recommended for First Run)
docker compose --profile core up -dOption B: Core + GPU AI Services
docker compose --profile core --profile anim up -dOption C: All Services (Resource Intensive)
docker compose --profile core --profile anim --profile disabled up -d# Check service status
docker compose ps
# Monitor startup logs
docker compose logs -f n8n-main n8n-queue-metrics n8n-dynamic-scaler
# Check health status
docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Health}}"- π§ N8N Workflow Editor:
https://n8n.yourdomain.com - π Traefik Dashboard:
https://traefik.yourdomain.com - π€ AI Agents API:
https://ai-agent.yourdomain.com/docs - π₯ Video Maker:
https://video-maker.yourdomain.com - π¨ Stable Diffusion:
https://stable-diffusion.yourdomain.com
The platform uses Docker Compose profiles to manage different service groups efficiently:
Essential services for N8N operation:
- N8N main instance, workers, and webhook handler
- PostgreSQL database and Redis queue
- Queue metrics monitoring and dynamic auto-scaling
- Traefik reverse proxy and Cloudflare tunnel
- Automated backup service
- Basic AI services (CPU-based video maker, AI agents)
- MinIO object storage and Baserow database
Resource Usage: ~8GB RAM, 4 CPU cores
GPU-accelerated AI services for advanced content generation:
- Stable Diffusion WebUI (image generation)
- Stable Video Diffusion via ComfyUI
- WAN2.1 Video Generation
- CogVideo (experimental video AI)
- CPU-optimized processing
Resource Usage: +16GB RAM, GPU required
Experimental and alternative services:
- ROCm-enabled alternatives to CPU services
- Development/testing versions
- Experimental AI models
Resource Usage: Variable
# Queue-based execution (required for auto-scaling)
EXECUTIONS_MODE=queue
QUEUE_BULL_REDIS_HOST=redis
QUEUE_HEALTH_CHECK_ACTIVE=true
# Performance tuning
N8N_CONCURRENCY_PRODUCTION_LIMIT=10 # Tasks per worker
N8N_QUEUE_BULL_GRACEFULSHUTDOWNTIMEOUT=300 # Graceful shutdown time
N8N_GRACEFUL_SHUTDOWN_TIMEOUT=300 # Total shutdown timeout
# Webhook configuration
N8N_WEBHOOK_URL=https://webhook.yourdomain.com
WEBHOOK_URL=https://webhook.yourdomain.com
# Security
N8N_SECURE_COOKIE=true
N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=trueThe dynamic scaler intelligently manages N8N workers based on real-time queue metrics:
# Scaling boundaries
MIN_REPLICAS=1 # Always keep at least 1 worker
MAX_REPLICAS=5 # Maximum concurrent workers
# Scaling triggers
SCALE_UP_QUEUE_THRESHOLD=5 # Scale up when queue > 5 jobs
SCALE_DOWN_QUEUE_THRESHOLD=0 # Scale down when queue empty
# Timing controls
POLLING_INTERVAL_SECONDS=30 # Check queue every 30 seconds
COOLDOWN_PERIOD_SECONDS=120 # Wait 2 minutes between scaling actions
# Queue configuration
QUEUE_NAME_PREFIX=bull # BullMQ prefix
QUEUE_NAME=jobs # Queue nameπ§ Scaling Logic:
- Monitor Redis queue depth every 30 seconds
- Scale Up: When queue length > threshold AND current replicas < max
- Scale Down: When queue length β€ threshold AND current replicas > min
- Cooldown: Prevent rapid scaling with configurable wait periods
- Gradual: Scale one worker at a time for stability
π₯ Short Video Maker:
PEXELS_API_KEY=your-key # For stock footage
VIDEO_CACHE_SIZE_IN_BYTES=1GB # Local cache size
WHISPER_MODEL=medium.en # Speech recognition modelπ€ AI Agents:
OPENAI_API_KEY=your-key # For GPT integration
LOG_LEVEL=debug # Logging verbosityπ¨ Stable Diffusion:
# CPU processing configuration
WEBUI_PORT=7860 # Web interface port
CPU_THREADS=4 # CPU thread utilizationMeta (Facebook/Instagram) page tokens and CTA links for the social-publishing
workflows. Tokens live in .env as the single source of truth (passed into
n8n via docker-compose.yml) rather than in n8n credentials β so they survive
workflow re-imports and rotate in one place. The page tokens are non-expiring;
they only break for Meta-side reasons (app/account flagged), never on an n8n
restart.
# Meta long-lived PAGE access tokens (Graph API page-token chain):
# user token -> long-lived user token -> GET /me/accounts -> page access_token
DIFFUSIONS_PAGE_TOKEN= # The Diffusions (LF2SH approved-upload-youtube.json)
# page 1206440389218995 / IG @the_diffusions
WTR_PAGE_TOKEN= # What's This Repo (5-publish-handler.json)
# page 1230772620115412 / IG @whatzthisrepo
# Cloaked CTA "free guide" link (301 -> Gumroad) appended to WTR descriptions
# and the YouTube comment auto-reply
WTR_GUIDE_URL=https://tinyurl.com/whatzthisrepo
# Baserow API token for the HOST-side daily IG/FB backfill cron
# (~/scripts/diffusions-backfill.sh -> systemd user timer `diffusions-backfill`).
# Read directly from .env by the wrapper; NOT injected into the n8n container.
BASEROW_API_TOKEN=
# WTR paced auto-dispatcher (host-side ~/scripts/wtr-dispatcher.sh -> systemd
# user timer `wtr-dispatcher`, ~every 90 min). Drains the WTR 'Approved' backlog
# in Baserow 751 at WTR_DAILY_GEN_LIMIT/day so it never starves the GPU shared
# with LF2SH. Read from .env by the wrapper; NOT injected into the n8n container.
WTR_GEN_WEBHOOK= # WTR generator webhook URL
WTR_DAILY_GEN_LIMIT=8 # max generations to start per day (default 8)The IG/FB nodes reference these as
{{$env.DIFFUSIONS_PAGE_TOKEN}}/{{$env.WTR_PAGE_TOKEN}}. After editing token values, recreate n8n so the new env is loaded:docker compose up -d n8n-main n8n-worker n8n-webhook(a plainrestartwill not pick up changed env values).
Real-time Redis queue monitoring with structured logging:
# View queue metrics
docker compose logs -f n8n-queue-metrics
# Example output:
# 2024-01-01T12:00:00 [INFO] Queue metrics queue=bull:jobs waiting_jobs=3
# 2024-01-01T12:00:00 [INFO] Detailed queue stats wait=3 active=2 completed=45 failed=0Features:
- β Multi-pattern BullMQ support (v3+, v4+, legacy)
- β Automatic Redis reconnection with exponential backoff
- β Structured JSON logging with timestamps
- β Health checks and error recovery
Intelligent auto-scaling with decision logging:
# Monitor scaling decisions
docker compose logs -f n8n-dynamic-scaler
# Example output:
# 2024-01-01T12:00:00 [INFO] Current metrics queue_length=7 current_replicas=2
# 2024-01-01T12:00:00 [INFO] Scaling decision made target_replicas=3 reason="Queue length 7 > threshold 5"
# 2024-01-01T12:00:00 [INFO] Scaling completed successfully new_replicas=3Features:
- β Predictive scaling based on queue trends
- β Docker Compose integration for seamless scaling
- β Configuration validation and setup checks
- β Graceful error handling and recovery
# Check all service health
docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Health}}"
# View service resource usage
docker stats --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"
# Monitor specific service logs
docker compose logs --tail=100 -f service-nameDaily Backups Include:
- PostgreSQL database dumps
- N8N workflows and credentials
- Binary data and configurations
- Retention: 7 days automatic cleanup
# Manual backup
docker compose exec n8n-backup sh -c "
BACKUP_DATE=\$(date +%Y%m%d-%H%M%S)
pg_dump -h postgres -U postgres -d n8n_db > /backups/manual-\$BACKUP_DATE.sql
tar -czf /backups/manual-backup-\$BACKUP_DATE.tar.gz -C /source .
"
# View available backups
ls -la ./daily-backups/
# Restore from backup
docker compose down
docker compose run --rm postgres psql -h postgres -U postgres -d n8n_db < backup.sql
tar -xzf backup.tar.gz -C ./backups/
docker compose --profile core up -dVolume Mappings:
./backups/n8n-data β N8N application data
./backups/n8n-workflows β Workflow definitions
./backups/n8n-credentials β Encrypted credentials
./backups/n8n-binary β Binary data storage
./postgres-data/pgdata β Database files
./videos β Generated video content
./data/minio β Object storage
π Symbolic Links for Data Continuity: The system uses symbolic links to maintain data continuity when moving between directories, ensuring your workflows and data remain intact during deployments.
# Add custom nodes
mkdir -p ./services/custom-nodes
# Place your node packages here - they'll be auto-mounted- Define in docker-compose.yml:
my-ai-service:
image: my-ai-service:latest
container_name: n8n-my-ai-service
restart: unless-stopped
profiles:
- core
networks:
- n8n-network
environment:
- API_KEY=${MY_AI_API_KEY}
labels:
- "traefik.enable=true"
- "traefik.http.routers.my-ai.rule=Host(`${MY_AI_HOST}`)"
- "traefik.http.routers.my-ai.entrypoints=web"- Add to .env:
MY_AI_HOST=my-ai.yourdomain.com
MY_AI_API_KEY=your-api-key- Update .env.example with placeholders
High-Volume Workflows:
# Increase worker capacity
MAX_REPLICAS=10
N8N_CONCURRENCY_PRODUCTION_LIMIT=20
# Database optimization
POSTGRES_SHARED_BUFFERS=256MB
POSTGRES_MAX_CONNECTIONS=200
# Redis optimization
REDIS_MAXMEMORY=2gb
REDIS_MAXMEMORY_POLICY=allkeys-lruCPU Processing:
# Verify CPU resources
nproc # Check available CPU cores
free -h # Check available memoryβ Services won't start:
# Check configuration syntax
docker compose config
# Validate environment variables
docker compose config | grep -A5 -B5 ERROR
# Check resource availability
docker system df
free -hβ N8N can't connect to database:
# Verify PostgreSQL health
docker compose exec postgres pg_isready -U postgres
# Check credentials consistency
grep -E "POSTGRES_(USER|PASSWORD|DB)" .env
# View database logs
docker compose logs postgresβ Auto-scaling not working:
# Check queue metrics service
docker compose logs n8n-queue-metrics
# Verify scaler decisions
docker compose logs n8n-dynamic-scaler
# Test Docker socket access
docker compose exec n8n-dynamic-scaler docker ps
# Manual queue inspection
docker compose exec redis redis-cli LLEN bull:jobs:waitβ AI services failing:
# Check CPU and memory resources
nproc
free -h
# Memory issues
dmesg | grep -i "killed process"
docker stats
# Check CPU usage
top -p $(docker inspect --format='{{.State.Pid}}' container-name)β Cloudflare tunnel issues:
# Verify tunnel token
docker compose logs n8n-cloudflared
# Test connectivity
curl -H "CF-Connecting-IP: 1.2.3.4" http://localhost/healthView comprehensive logs:
# All services
docker compose logs --tail=100 -f
# Filter by profile
docker compose logs -f $(docker compose ps --services --filter profile=core)
# Error hunting
docker compose logs 2>&1 | grep -i -C3 error
# Performance monitoring
docker compose logs | grep -E "(memory|cpu|performance)"Complete system reset:
# Stop all services
docker compose down
# Clean containers and volumes (β οΈ DATA LOSS)
docker compose down -v
docker system prune -af
# Restore from backup
tar -xzf latest-backup.tar.gz -C ./
docker compose --profile core up -dPartial service restart:
# Restart specific services
docker compose restart n8n-main n8n-worker
# Rebuild and restart
docker compose up -d --force-recreate n8n-mainFormat: https://webhook.yourdomain.com/webhook/{workflow-id}
Example N8N Workflow:
- Webhook Trigger β Set to production URL
- Queue Job β Process with available workers
- AI Service Call β Use internal service URLs
- Response β Return via webhook
Set up comprehensive monitoring:
# Add Prometheus + Grafana (optional)
# Monitor queue metrics, system resources, and AI service performance
# Custom dashboards for workflow success ratesWe welcome contributions! Here's how to get started:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes with proper documentation
- Test thoroughly:
docker compose config && docker compose --profile core up -d - Submit a pull request
Development Guidelines:
- Follow existing code structure and naming conventions
- Update documentation for any new features
- Add appropriate health checks for new services
- Test with multiple profiles and configurations
This project is licensed under the MIT License - see the LICENSE file for details.
- N8N Community - For the amazing workflow automation platform
- Docker Team - For containerization technology
- AI/ML Communities - For open-source models and tools
- Contributors - For continuous improvements and bug fixes
π Platform Status: Production Ready β
π Auto-scaling: Active β
π€ AI Services: Integrated β
π Documentation: Comprehensive β
Generated with Claude Code
Co-Authored-By: Claude noreply@anthropic.com