Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

n8n Multi-Main Setup with Docker Compose

This repository contains a production-ready n8n setup using Docker Compose with multi-main architecture, Nginx load balancer, scalable workers, Redis queue management, and PostgreSQL database.

⚠️ Important: This Docker Compose setup supports manual scaling only. For automatic scaling based on CPU/memory metrics, you need to migrate to Kubernetes (with HPA) or Docker Swarm (with external auto-scaling tools).

Architecture Overview

                   ┌────────────────────┐
                   │  Nginx LB (Port 80)│
                   │  Load Balancer     │
                   └──────────┬─────────┘
                              │
                 ┌────────────┴───────────┐
                 │                        │
      ┌──────────▼──────────┐  ┌─────────▼──────────┐
      │   n8n-main-1        │  │   n8n-main-2       │
      │   (Internal: 5678)  │  │   (Internal: 5678) │
      │   UI + API          │  │   UI + API         │
      └──────────┬──────────┘  └─────────┬──────────┘
                 │                       │
                 └───────────┬───────────┘
                             │
                    ┌────────▼────────┐
                    │  Redis Queue    │
                    │  (Bull Queue)   │
                    └────────┬────────┘
                             │
              ┌──────────────┼──────────────┐
              │              │              │
       ┌──────▼──────┐ ┌────▼─────┐ ┌─────▼──────┐
       │ n8n-worker-1│ │n8n-worker│ │n8n-worker-N│
       │  (Executor) │ │    -2    │ │  (Scale)   │
       └──────┬──────┘ └────┬─────┘ └─────┬──────┘
              │             │              │
              └─────────────┼──────────────┘
                            │
                   ┌────────▼────────┐
                   │   PostgreSQL    │
                   │   (Database)    │
                   └─────────────────┘

Components

  1. Nginx Load Balancer

    • Single entry point for all traffic (HTTP: port 80, HTTPS: port 443)
    • Distributes requests between n8n main instances
    • Least-connections load balancing algorithm
    • WebSocket support for real-time features
    • Health checks with automatic failover
  2. n8n Main Instances (2)

    • Handle web UI, API requests, and webhooks
    • Push workflow executions to Redis queue
    • Provide high availability and load distribution
    • Internal port 5678 (only accessible via Nginx)
  3. n8n Workers (2+)

    • Pull and execute workflows from Redis queue
    • Manually scalable with Docker Compose (auto-scaling requires Kubernetes/Swarm)
    • Run in background without UI
    • Can scale horizontally as needed
  4. Redis

    • Queue management using Bull Queue
    • Coordinates workflow distribution
    • Temporary container (will migrate to Azure Redis)
  5. PostgreSQL

    • Stores workflow definitions, credentials, and execution history
    • Temporary container (will migrate to AWS RDS)

Prerequisites

  • Docker Engine 20.10+
  • Docker Compose 2.0+
  • Minimum 4GB RAM
  • 10GB disk space

Quick Start

1. Clone and Setup Environment

# Copy the example environment file
cp .env.example .env

# Edit the .env file with your configuration
nano .env  # or use your preferred editor

2. Configure Required Variables

Edit .env and update these critical values:

# Generate secure passwords
openssl rand -base64 32  # Use for POSTGRES_PASSWORD
openssl rand -base64 32  # Use for REDIS_PASSWORD
openssl rand -hex 32     # Use for N8N_ENCRYPTION_KEY

# Update in .env
POSTGRES_PASSWORD=<generated_password_1>
REDIS_PASSWORD=<generated_password_2>
N8N_ENCRYPTION_KEY=<generated_key>

⚠️ IMPORTANT: Never change N8N_ENCRYPTION_KEY after initial setup! This will make all existing credentials unreadable.

3. Start the Stack

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f

# Check service health
docker-compose ps

4. Access n8n

The Nginx load balancer automatically distributes traffic between both main instances (n8n-main-1 and n8n-main-2). You only need to access the single Nginx endpoint.

Note: The main instances are not directly accessible from the host - all traffic goes through Nginx.

Environment Variables

All environment variables are documented in .env.example. Key categories:

Database (PostgreSQL)

POSTGRES_USER=n8n
POSTGRES_PASSWORD=<secure_password>
POSTGRES_DB=n8n
DB_POSTGRESDB_HOST=postgres  # Change to RDS endpoint for AWS
DB_POSTGRESDB_PORT=5432

Queue (Redis)

REDIS_PASSWORD=<secure_password>
QUEUE_BULL_REDIS_HOST=redis  # Change to Azure Redis endpoint
QUEUE_BULL_REDIS_PORT=6379
QUEUE_BULL_REDIS_DB=0

n8n Core

N8N_HOST=localhost  # Your domain in production
N8N_PROTOCOL=http   # Use https in production
WEBHOOK_URL=http://localhost:5678/
N8N_ENCRYPTION_KEY=<32_character_hex_key>

Worker Resources

WORKER_CPU_LIMIT=1.0            # Max CPU per worker
WORKER_CPU_RESERVATION=0.25     # Min CPU per worker
WORKER_MEMORY_LIMIT=1G          # Max memory per worker
WORKER_MEMORY_RESERVATION=256M  # Min memory per worker

Scaling Workers

Important: Docker Compose Limitations

Docker Compose does NOT support automatic scaling based on CPU or memory usage. The deploy.resources section in the docker-compose.yml only defines resource limits for each container but does not trigger automatic scaling.

With Docker Compose, you can:

  • ✅ Manually scale workers up or down
  • ✅ Set resource limits (CPU/memory) per worker
  • ❌ NOT automatically scale based on resource metrics

For true auto-scaling based on CPU/memory usage, you must use Docker Swarm or Kubernetes.

Manual Scaling (Docker Compose)

Scale workers manually using Docker Compose:

# Scale to 5 workers
docker-compose up -d --scale n8n-worker-1=5

# Scale down to 2 workers
docker-compose up -d --scale n8n-worker-1=2

# Or add more worker services in docker-compose.yml

Resource Limits (Docker Compose)

Workers are configured with CPU and memory limits to control resource allocation per container:

deploy:
  resources:
    limits:
      cpus: '1.0'      # Maximum 1 CPU core
      memory: 1G       # Maximum 1GB RAM
    reservations:
      cpus: '0.25'     # Minimum 0.25 CPU core
      memory: 256M     # Minimum 256MB RAM

Note: These limits prevent individual workers from consuming too many resources but do NOT trigger automatic scaling.

Automatic Scaling (Requires Docker Swarm or Kubernetes)

For production auto-scaling based on CPU/memory metrics, you must migrate from Docker Compose to:

  1. Docker Swarm Mode (Manual Scaling, Easier Orchestration)

    • Docker Swarm makes manual scaling easier but does NOT have built-in auto-scaling based on metrics
    • You would need external tools (like Orbiter, Docker Swarm Autoscaler) for automatic scaling
    • Best for: Simpler deployments where manual scaling is acceptable
    docker swarm init
    docker stack deploy -c docker-compose.yml n8n
    
    # Manual scaling in Swarm
    docker service scale n8n_n8n-worker-1=5
    
    # Check worker status
    docker service ls
  2. Kubernetes (True Auto-Scaling with HPA)

    • Kubernetes has native auto-scaling support with Horizontal Pod Autoscaler (HPA)
    • Automatically scales workers based on CPU/Memory metrics
    • Best for: Production environments requiring automatic scaling
    • Example HPA configuration:
    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: n8n-worker-hpa
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: n8n-worker
      minReplicas: 2
      maxReplicas: 10
      metrics:
      - type: Resource
        resource:
          name: cpu
          target:
            type: Utilization
            averageUtilization: 70
      - type: Resource
        resource:
          name: memory
          target:
            type: Utilization
            averageUtilization: 80
  3. Monitoring Stack

    • Prometheus + Grafana for metrics
    • Monitor queue depth, worker CPU/memory
    • Alert on high queue depth or worker saturation

Load Balancing

Nginx Load Balancer (Included)

This setup includes an Nginx load balancer that's already configured and ready to use. No additional setup required!

Features:

  • ✅ Least-connections load balancing algorithm
  • ✅ WebSocket support for n8n real-time features
  • ✅ Health checks with automatic failover
  • ✅ Configurable via nginx.conf
  • ✅ SSL/TLS ready (commented out in config)

Nginx Configuration

The nginx.conf file is located in the project root. Key configuration points:

upstream n8n_backend {
    least_conn;
    server n8n-main-1:5678 max_fails=3 fail_timeout=30s;
    server n8n-main-2:5678 max_fails=3 fail_timeout=30s;
}

Enabling HTTPS/SSL

To enable HTTPS:

  1. Place SSL certificates in the ssl/ directory:

    mkdir -p ssl
    # Copy your certificate files
    cp /path/to/cert.pem ssl/
    cp /path/to/key.pem ssl/
  2. Edit nginx.conf and uncomment the HTTPS server block (lines starting with # server {)

  3. Update .env:

    N8N_PROTOCOL=https
    WEBHOOK_URL=https://your-domain.com/
  4. Restart services:

    docker-compose restart nginx

Custom Nginx Configuration

You can modify nginx.conf to:

  • Change load balancing algorithm (least_conn, ip_hash, round_robin)
  • Adjust timeouts and buffer sizes
  • Add rate limiting
  • Configure custom headers
  • Set up access restrictions

After modifying nginx.conf, restart Nginx:

docker-compose restart nginx

Monitoring Nginx

Check Nginx logs:

# Access logs
docker-compose logs nginx

# Follow logs in real-time
docker-compose logs -f nginx

# Nginx status (if enabled)
curl http://localhost/nginx_status

Migration to Cloud Services

PostgreSQL Migration (AWS RDS)

  1. Create RDS PostgreSQL Instance

    • Engine: PostgreSQL 16
    • Instance class: db.t3.medium (or larger)
    • Storage: GP3 (100GB+)
    • Enable automated backups
  2. Export Current Data

    # Create backup
    docker-compose exec postgres pg_dump -U n8n n8n > n8n_backup.sql
  3. Import to RDS

    # Import to RDS
    psql -h your-rds-endpoint.region.rds.amazonaws.com \
         -U your_rds_user \
         -d your_rds_database \
         < n8n_backup.sql
  4. Update .env

    DB_POSTGRESDB_HOST=your-rds-endpoint.region.rds.amazonaws.com
    DB_POSTGRESDB_PORT=5432
    POSTGRES_USER=your_rds_user
    POSTGRES_PASSWORD=your_rds_password
    POSTGRES_DB=your_rds_database
  5. Remove PostgreSQL Service

    • Comment out or remove postgres service from docker-compose.yml
    • Restart stack: docker-compose up -d

Redis Migration (Azure Cache for Redis)

  1. Create Azure Redis Instance

    • Tier: Standard or Premium
    • Version: 6.x or 7.x
    • Enable SSL/TLS
  2. Get Connection Details

    • Host: your-redis.redis.cache.windows.net
    • Port: 6380 (SSL) or 6379 (non-SSL)
    • Access Key: From Azure Portal
  3. Update .env

    QUEUE_BULL_REDIS_HOST=your-redis.redis.cache.windows.net
    QUEUE_BULL_REDIS_PORT=6380
    REDIS_PASSWORD=your_azure_access_key
  4. For SSL Connection Add to main and worker environment:

    QUEUE_BULL_REDIS_TLS=true
  5. Remove Redis Service

    • Comment out or remove redis service from docker-compose.yml
    • Restart stack: docker-compose up -d

Management Commands

Start Services

docker-compose up -d

Stop Services

docker-compose down

View Logs

# All services
docker-compose logs -f

# Specific service
docker-compose logs -f n8n-main-1
docker-compose logs -f n8n-worker-1

Restart Services

# All services
docker-compose restart

# Specific service
docker-compose restart n8n-main-1

Check Status

docker-compose ps

Scale Workers

# Scale to 5 workers
docker-compose up -d --scale n8n-worker-1=5

Database Backup

# Create backup
docker-compose exec postgres pg_dump -U n8n n8n > backup_$(date +%Y%m%d_%H%M%S).sql

# Restore backup
docker-compose exec -T postgres psql -U n8n n8n < backup_20240101_120000.sql

Redis CLI Access

# Access Redis CLI
docker-compose exec redis redis-cli -a ${REDIS_PASSWORD}

# Check queue depth
LLEN bull:n8n:queue

Troubleshooting

Workers Not Processing Jobs

  1. Check Redis connection:

    docker-compose logs n8n-worker-1 | grep -i redis
  2. Verify queue mode is enabled:

    docker-compose exec n8n-main-1 env | grep EXECUTIONS_MODE
    # Should show: EXECUTIONS_MODE=queue
  3. Check Redis queue:

    docker-compose exec redis redis-cli -a ${REDIS_PASSWORD} LLEN bull:n8n:queue

Database Connection Issues

  1. Check PostgreSQL health:

    docker-compose exec postgres pg_isready -U n8n
  2. Test connection:

    docker-compose exec postgres psql -U n8n -d n8n -c "SELECT 1;"

High Memory Usage

  1. Monitor worker memory:

    docker stats n8n-worker-1 n8n-worker-2
  2. Adjust limits in .env:

    WORKER_MEMORY_LIMIT=2G  # Increase if needed
  3. Scale horizontally instead of vertically:

    docker-compose up -d --scale n8n-worker-1=4

Workflow Timeouts

  1. Increase timeout in .env:

    EXECUTIONS_TIMEOUT=600        # 10 minutes
    EXECUTIONS_TIMEOUT_MAX=7200   # 2 hours
  2. Restart services:

    docker-compose restart

Security Considerations

Production Checklist

  • Use strong, unique passwords for all services
  • Never commit .env file to version control
  • Use HTTPS in production (N8N_PROTOCOL=https)
  • Enable firewall rules for database and Redis
  • Use SSL/TLS for Redis connections
  • Enable PostgreSQL SSL connections
  • Regularly backup database
  • Keep n8n and Docker images updated
  • Use secrets management (AWS Secrets Manager, Azure Key Vault)
  • Enable authentication for n8n UI
  • Restrict network access to internal services

Environment Variables Protection

Never expose sensitive variables:

# Add to .gitignore
.env
.env.local
.env.*.local

Use Docker secrets in production:

secrets:
  postgres_password:
    file: ./secrets/postgres_password.txt
  redis_password:
    file: ./secrets/redis_password.txt

Performance Tuning

Worker Optimization

  1. CPU-bound workflows: Increase worker count

    docker-compose up -d --scale n8n-worker-1=10
  2. Memory-intensive workflows: Increase memory limits

    WORKER_MEMORY_LIMIT=2G
  3. I/O-bound workflows: Workers can handle more concurrency

Database Optimization

  1. Connection pooling: Increase pool size

    DB_POSTGRESDB_POOL_SIZE=20
  2. Query performance: Add indexes for frequently queried fields

  3. Vacuum regularly: For PostgreSQL maintenance

    docker-compose exec postgres psql -U n8n -d n8n -c "VACUUM ANALYZE;"

Redis Optimization

  1. Memory management: Monitor Redis memory usage

    docker-compose exec redis redis-cli -a ${REDIS_PASSWORD} INFO memory
  2. Persistence: Configure RDB or AOF based on requirements

  3. Eviction policy: Set appropriate maxmemory-policy

Monitoring

Health Checks

All services include health checks:

# Check all services
docker-compose ps

# Manual health check
curl http://localhost:5678/healthz

Metrics Collection

Add Prometheus monitoring:

# docker-compose.yml
services:
  prometheus:
    image: prom/prometheus
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
    ports:
      - "9090:9090"

  grafana:
    image: grafana/grafana
    ports:
      - "3000:3000"

Log Aggregation

Use centralized logging:

# Forward logs to external system
docker-compose logs -f | your-log-aggregator

Support

License

This configuration is provided as-is. Please refer to n8n's license for the n8n software itself.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors