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.
┌────────────────────┐
│ 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) │
└─────────────────┘
-
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
-
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)
-
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
-
Redis
- Queue management using Bull Queue
- Coordinates workflow distribution
- Temporary container (will migrate to Azure Redis)
-
PostgreSQL
- Stores workflow definitions, credentials, and execution history
- Temporary container (will migrate to AWS RDS)
- Docker Engine 20.10+
- Docker Compose 2.0+
- Minimum 4GB RAM
- 10GB disk space
# Copy the example environment file
cp .env.example .env
# Edit the .env file with your configuration
nano .env # or use your preferred editorEdit .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>N8N_ENCRYPTION_KEY after initial setup! This will make all existing credentials unreadable.
# Start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Check service health
docker-compose ps- Via Nginx Load Balancer: http://localhost
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.
All environment variables are documented in .env.example. Key categories:
POSTGRES_USER=n8n
POSTGRES_PASSWORD=<secure_password>
POSTGRES_DB=n8n
DB_POSTGRESDB_HOST=postgres # Change to RDS endpoint for AWS
DB_POSTGRESDB_PORT=5432REDIS_PASSWORD=<secure_password>
QUEUE_BULL_REDIS_HOST=redis # Change to Azure Redis endpoint
QUEUE_BULL_REDIS_PORT=6379
QUEUE_BULL_REDIS_DB=0N8N_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_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 workerDocker 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.
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.ymlWorkers 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 RAMNote: These limits prevent individual workers from consuming too many resources but do NOT trigger automatic scaling.
For production auto-scaling based on CPU/memory metrics, you must migrate from Docker Compose to:
-
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
-
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
-
Monitoring Stack
- Prometheus + Grafana for metrics
- Monitor queue depth, worker CPU/memory
- Alert on high queue depth or worker saturation
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)
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;
}To enable HTTPS:
-
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/ -
Edit
nginx.confand uncomment the HTTPS server block (lines starting with# server {) -
Update
.env:N8N_PROTOCOL=https WEBHOOK_URL=https://your-domain.com/
-
Restart services:
docker-compose restart nginx
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 nginxCheck 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-
Create RDS PostgreSQL Instance
- Engine: PostgreSQL 16
- Instance class: db.t3.medium (or larger)
- Storage: GP3 (100GB+)
- Enable automated backups
-
Export Current Data
# Create backup docker-compose exec postgres pg_dump -U n8n n8n > n8n_backup.sql
-
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
-
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
-
Remove PostgreSQL Service
- Comment out or remove
postgresservice fromdocker-compose.yml - Restart stack:
docker-compose up -d
- Comment out or remove
-
Create Azure Redis Instance
- Tier: Standard or Premium
- Version: 6.x or 7.x
- Enable SSL/TLS
-
Get Connection Details
- Host:
your-redis.redis.cache.windows.net - Port: 6380 (SSL) or 6379 (non-SSL)
- Access Key: From Azure Portal
- Host:
-
Update .env
QUEUE_BULL_REDIS_HOST=your-redis.redis.cache.windows.net QUEUE_BULL_REDIS_PORT=6380 REDIS_PASSWORD=your_azure_access_key
-
For SSL Connection Add to main and worker environment:
QUEUE_BULL_REDIS_TLS=true
-
Remove Redis Service
- Comment out or remove
redisservice fromdocker-compose.yml - Restart stack:
docker-compose up -d
- Comment out or remove
docker-compose up -ddocker-compose down# All services
docker-compose logs -f
# Specific service
docker-compose logs -f n8n-main-1
docker-compose logs -f n8n-worker-1# All services
docker-compose restart
# Specific service
docker-compose restart n8n-main-1docker-compose ps# Scale to 5 workers
docker-compose up -d --scale n8n-worker-1=5# 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# Access Redis CLI
docker-compose exec redis redis-cli -a ${REDIS_PASSWORD}
# Check queue depth
LLEN bull:n8n:queue-
Check Redis connection:
docker-compose logs n8n-worker-1 | grep -i redis -
Verify queue mode is enabled:
docker-compose exec n8n-main-1 env | grep EXECUTIONS_MODE # Should show: EXECUTIONS_MODE=queue
-
Check Redis queue:
docker-compose exec redis redis-cli -a ${REDIS_PASSWORD} LLEN bull:n8n:queue
-
Check PostgreSQL health:
docker-compose exec postgres pg_isready -U n8n -
Test connection:
docker-compose exec postgres psql -U n8n -d n8n -c "SELECT 1;"
-
Monitor worker memory:
docker stats n8n-worker-1 n8n-worker-2
-
Adjust limits in
.env:WORKER_MEMORY_LIMIT=2G # Increase if needed -
Scale horizontally instead of vertically:
docker-compose up -d --scale n8n-worker-1=4
-
Increase timeout in
.env:EXECUTIONS_TIMEOUT=600 # 10 minutes EXECUTIONS_TIMEOUT_MAX=7200 # 2 hours
-
Restart services:
docker-compose restart
- Use strong, unique passwords for all services
- Never commit
.envfile 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
Never expose sensitive variables:
# Add to .gitignore
.env
.env.local
.env.*.localUse Docker secrets in production:
secrets:
postgres_password:
file: ./secrets/postgres_password.txt
redis_password:
file: ./secrets/redis_password.txt-
CPU-bound workflows: Increase worker count
docker-compose up -d --scale n8n-worker-1=10
-
Memory-intensive workflows: Increase memory limits
WORKER_MEMORY_LIMIT=2G
-
I/O-bound workflows: Workers can handle more concurrency
-
Connection pooling: Increase pool size
DB_POSTGRESDB_POOL_SIZE=20
-
Query performance: Add indexes for frequently queried fields
-
Vacuum regularly: For PostgreSQL maintenance
docker-compose exec postgres psql -U n8n -d n8n -c "VACUUM ANALYZE;"
-
Memory management: Monitor Redis memory usage
docker-compose exec redis redis-cli -a ${REDIS_PASSWORD} INFO memory
-
Persistence: Configure RDB or AOF based on requirements
-
Eviction policy: Set appropriate maxmemory-policy
All services include health checks:
# Check all services
docker-compose ps
# Manual health check
curl http://localhost:5678/healthzAdd 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"Use centralized logging:
# Forward logs to external system
docker-compose logs -f | your-log-aggregator- n8n Documentation: https://docs.n8n.io
- Community Forum: https://community.n8n.io
- GitHub Issues: https://github.com/n8n-io/n8n/issues
This configuration is provided as-is. Please refer to n8n's license for the n8n software itself.