x-defaults: &defaults
  restart: unless-stopped
  logging:
    driver: json-file
    options:
      max-size: 100m
      max-file: '3'

services:
  n8n:
    <<: *defaults
    image: ${GLOBAL_REGISTRY:-}n8nio/n8n:${N8N_VERSION:-1.114.0}
    ports:
      - '${N8N_PORT:-5678}:5678'
    volumes:
      - n8n_data:/home/node/.n8n
    environment:
      - TZ=${TZ:-UTC}
      - N8N_BASIC_AUTH_ACTIVE=${N8N_BASIC_AUTH_ACTIVE:-true}
      - N8N_BASIC_AUTH_USER=${N8N_BASIC_AUTH_USER:-}
      - N8N_BASIC_AUTH_PASSWORD=${N8N_BASIC_AUTH_PASSWORD:-}
      - N8N_HOST=${N8N_HOST:-0.0.0.0}
      - N8N_PORT=${N8N_PORT:-5678}
      - N8N_PROTOCOL=${N8N_PROTOCOL:-http}
      - WEBHOOK_URL=${WEBHOOK_URL:-http://localhost:5678/}
      - GENERIC_TIMEZONE=${GENERIC_TIMEZONE:-UTC}
      # Database configuration (optional, uses SQLite by default)
      - DB_TYPE=${DB_TYPE:-sqlite}
      - DB_POSTGRESDB_DATABASE=${DB_POSTGRESDB_DATABASE:-n8n}
      - DB_POSTGRESDB_HOST=${DB_POSTGRESDB_HOST:-n8n-db}
      - DB_POSTGRESDB_PORT=${DB_POSTGRESDB_PORT:-5432}
      - DB_POSTGRESDB_USER=${DB_POSTGRESDB_USER:-n8n}
      - DB_POSTGRESDB_PASSWORD=${DB_POSTGRESDB_PASSWORD:-}
      # Execution mode
      - EXECUTIONS_MODE=${EXECUTIONS_MODE:-regular}
      - N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY:-}
    depends_on:
      n8n-db:
        condition: service_healthy
    profiles:
      - default
    deploy:
      resources:
        limits:
          cpus: ${N8N_CPU_LIMIT:-2.0}
          memory: ${N8N_MEMORY_LIMIT:-2G}
        reservations:
          cpus: ${N8N_CPU_RESERVATION:-0.5}
          memory: ${N8N_MEMORY_RESERVATION:-512M}
    healthcheck:
      test: [CMD, wget, --no-verbose, --tries=1, --spider, 'http://localhost:5678/healthz']
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 30s

  n8n-db:
    <<: *defaults
    image: ${GLOBAL_REGISTRY:-}postgres:${POSTGRES_VERSION:-17.2-alpine3.21}
    environment:
      - TZ=${TZ:-UTC}
      - POSTGRES_USER=${POSTGRES_USER:-n8n}
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-}
      - POSTGRES_DB=${POSTGRES_DB:-n8n}
    volumes:
      - n8n_db_data:/var/lib/postgresql/data
    deploy:
      resources:
        limits:
          cpus: ${N8N_DB_CPU_LIMIT:-1.0}
          memory: ${N8N_DB_MEMORY_LIMIT:-1G}
        reservations:
          cpus: ${N8N_DB_CPU_RESERVATION:-0.5}
          memory: ${N8N_DB_MEMORY_RESERVATION:-512M}

volumes:
  n8n_data:
  n8n_db_data:
