n8nDockerCloudflare Tunnelcloudflaredself-hosted

n8n + Cloudflare Tunnel Setup — Self-Hosting on Your Domain

·8 min read

Step 1: Directory and Docker Compose


Create the project directory:



mkdir -p ~/projects/n8n
cd ~/projects/n8n

Create docker-compose.yml:



services:
  n8n:
    image: n8nio/n8n:latest
    container_name: n8n
    restart: unless-stopped
    ports:
      - "5679:5678"
    environment:
      - N8N_HOST=n8n.yourdomain.com
      - N8N_PORT=5678
      - N8N_PROTOCOL=https
      - N8N_EDITOR_BASE_URL=https://n8n.yourdomain.com
      - WEBHOOK_URL=https://n8n.yourdomain.com/
      - N8N_DEFAULT_BINARY_DATA_MODE=filesystem
      - N8N_PROXY_HOPS=1
      - N8N_RUNNERS_ENABLED=true
      - GENERIC_TIMEZONE=UTC
    volumes:
      - n8n_data:/home/node/.n8n
    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://localhost:5678/healthz"]
      interval: 30s
      timeout: 10s
      retries: 5

volumes:
  n8n_data:
    driver: local

networks:
  default:
    name: openwa-network

Replace n8n.yourdomain.com with your actual subdomain throughout.


Key Environment Variables Explained


N8N_HOST and N8N_EDITOR_BASE_URL must match your tunnel hostname exactly. n8n uses these to generate callback URLs in webhook responses, OAuth redirect URIs, and credential test payloads. If they do not match the browser URL, credential tests fail silently and workflows generate broken URLs.


N8N_PROTOCOL=https — n8n must know it is behind HTTPS even when the local connection is HTTP. Without this, internal links and form actions generate as http:// instead of https://.


N8N_PROXY_HOPS=1 — critical when behind Cloudflare Tunnel. n8n reads the X-Forwarded-Proto header to determine the protocol. Setting this to 1 tells n8n to trust one proxy layer. If you run additional reverse proxies in front of cloudflared, increment this value accordingly.


N8N_RUNNERS_ENABLED=true — enables the separate worker process for asynchronous workflow execution. Disabled by default. Production use always enables this — it prevents long-running workflows from blocking the main web server.


N8N_DEFAULT_BINARY_DATA_MODE=filesystem — stores workflow binary data on the filesystem instead of the database. Keep this. The alternative bloats your database and slows down workflow execution.


Step 2: Install cloudflared


cloudflared creates the tunnel from your server to Cloudflare.


On Ubuntu/Debian:



sudo apt install cloudflared

On other distros or if the package is outdated, download the binary directly:



curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o /usr/local/bin/cloudflared
chmod +x /usr/local/bin/cloudflared

Verify:



cloudflared --version

Step 3: Create the Cloudflare Tunnel


Log into Cloudflare Zero Trust: dash.cloudflare.com → Zero Trust → Networks → Tunnels → Create a tunnel → Cloudflared → Give it a name like n8n-proxy.


Cloudflare will show an install command with your tunnel token. Run:



cloudflared tunnel create n8n-proxy

This creates a credentials file at ~/.cloudflared/.json. Keep it safe.


Step 4: Configure the Tunnel Ingress Rules


Create ~/.cloudflared/n8n-proxy.yml:



tunnel: n8n-proxy
credentials-file: ~/.cloudflared/.json
origincert: ~/.cloudflared/cert.pem

ingress:
  - hostname: n8n.yourdomain.com
    service: http://localhost:5679
  - service: http_status:404

The tunnel connects to localhost:5679 — the Docker host port where n8n is mapped (container port 5678 mapped to host 5679). cloudflared runs on the host, not inside a container, so it connects to the host port.


Step 5: Route the Domain


In Cloudflare Zero Trust dashboard, go to the tunnel's Routes section. Add a route:


  • Subdomain: n8n
  • Domain: yourdomain.com
  • Type: CNAME
  • Target: n8n-proxy

  • Cloudflare handles TLS termination at the edge. Your server never sees a plain HTTP request.


    Step 6: Start Everything


    
    cd ~/projects/n8n
    sudo docker compose up -d
    

    Wait for n8n to start, then start the tunnel:


    
    cloudflared --config ~/.cloudflared/n8n-proxy.yml tunnel run n8n-proxy
    

    Or use n8nctl which wraps both commands with health checks.


    Verify the Tunnel is Live


    The cloudflared log should show:


    
    Registered tunnel connection connIndex=0 location=blr02 protocol=quic
    

    Cloudflare assigns the nearest edges. A healthy tunnel shows 4 connections — one per edge pair. Multiple locations (blr02, bom09, bom12) means Cloudflare is load-balancing across PoPs.


    Common issue — "Connection terminated" shortly after startup: this means cloudflared connected before n8n was ready. Restart the tunnel — n8n is already up, so the second connection succeeds immediately.


    Your n8n is Now Live


    Visit https://n8n.yourdomain.com. On first launch, n8n generates an encryption key for stored credentials and redirects you to the setup screen. Create your admin user.


    Back up the n8n_data Docker volume. All workflows and credentials live there. Without it, you lose everything on container rebuild.


    To back up:


    
    docker run --rm -v n8n_n8n_data:/data -v $(pwd):/backup alpine tar czf n8n-backup.tar.gz -C /data .
    

    Managing the Stack with n8nctl


    Once n8n and the tunnel are running, a small Bash wrapper makes day-to-day operation a single command.


    What n8nctl Does


    n8nctl is a Bash script that:


  • Starts or stops the n8n Docker container via docker compose
  • Starts or stops the Cloudflare Tunnel (cloudflared) in the background
  • Captures tunnel logs to a file for debugging
  • Checks tunnel health by grepping for "Registered tunnel connection"

  • No systemd, no supervisor. Just a script you can run manually or wire up to a cron check.


    The Script


    Save as ~/projects/n8n/n8nctl:


    
    #!/bin/bash
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    TUNNEL_CONFIG="$HOME/.cloudflared/n8n-proxy.yml"
    TUNNEL_NAME="n8n-proxy"
    LOG_FILE="$SCRIPT_DIR/tunnel2.log"
    
    stop_tunnel() {
        PIDS=$(pgrep -f "cloudflared.*n8n-proxy" 2>/dev/null || true)
        if [ -n "$PIDS" ]; then
            echo "Stopping tunnel (PID: $PIDS)..."
            echo "$PIDS" | xargs kill 2>/dev/null || true
            sleep 2
        fi
    }
    
    start_tunnel() {
        stop_tunnel
        echo "Starting n8n Cloudflare tunnel..."
        cloudflared --config "$TUNNEL_CONFIG" tunnel run "$TUNNEL_NAME" > "$LOG_FILE" 2>&1 &
        sleep 5
        if grep -q "Registered tunnel connection" "$LOG_FILE" 2>/dev/null; then
            echo "Tunnel is live."
        else
            echo "Warning: tunnel may not be connected. Check: tail -f $LOG_FILE"
        fi
    }
    
    case "${1:-}" in
        start)
            cd "$SCRIPT_DIR" && sudo docker compose up -d
            sleep 5
            start_tunnel
            ;;
        stop)
            cd "$SCRIPT_DIR" && sudo docker compose down
            stop_tunnel
            ;;
        restart)
            cd "$SCRIPT_DIR" && sudo docker compose restart
            sleep 5
            stop_tunnel
            start_tunnel
            ;;
        status)
            echo "=== n8n ==="
            sudo docker ps --filter "name=n8n" --format "table {{.Names}}	{{.Status}}	{{.Ports}}"
            echo ""
            echo "=== n8n tunnel ==="
            PIDS=$(pgrep -f "cloudflared.*n8n-proxy" 2>/dev/null || true)
            if [ -n "$PIDS" ]; then
                echo "Running (PID: $PIDS)"
            else
                echo "Not running"
            fi
            ;;
        logs)
            cd "$SCRIPT_DIR" && sudo docker compose logs -f
            ;;
        tunnel-logs)
            tail -f "$LOG_FILE"
            ;;
        *)
            echo "Usage: $0 {start|stop|restart|status|logs|tunnel-logs}"
            exit 1
            ;;
    esac
    

    Make it executable:


    
    chmod +x ~/projects/n8n/n8nctl
    

    Commands


  • ./n8nctl start — Start n8n + tunnel (waits 5s, checks tunnel health)
  • ./n8nctl stop — Stop n8n + tunnel
  • ./n8nctl restart — Restart n8n, reconnect tunnel
  • ./n8nctl status — Show container and tunnel running state
  • ./n8nctl logs — Tail n8n container logs (-f)
  • ./n8nctl tunnel-logs — Tail cloudflared tunnel logs (-f)

  • How the Tunnel Health Check Works


    After starting cloudflared, the script waits 5 seconds, then greps the tunnel log for "Registered tunnel connection". That string appears once per successful edge registration. If found, the tunnel is live. If not, it prints a warning.


    The tunnel log captures both stdout and stderr from cloudflared:


    
    cloudflared --config "$TUNNEL_CONFIG" tunnel run "$TUNNEL_NAME" > "$LOG_FILE" 2>&1 &
    

    The trailing & runs cloudflared in the background so the script returns immediately.


    stop_tunnel Uses pgrep


    The stop_tunnel function finds cloudflared processes by matching the command line:


    
    pgrep -f "cloudflared.*n8n-proxy"
    

    This is safer than killing by a hardcoded PID — it finds whatever process is currently running the n8n tunnel even if the script restarted it between sessions.


    What the Tunnel Log Tells You


    A healthy log entry:


    
    2026-06-23T06:47:38Z INF Starting tunnel tunnelID=cecb5bc3-8ea6-4651-b817-d2c49526988a
    2026-06-23T06:47:39Z INF Registered tunnel connection connIndex=0 connection=f9b19d2f... location=blr02 protocol=quic
    2026-06-23T06:47:39Z INF Registered tunnel connection connIndex=1 connection=ebcb380f... location=bom09 protocol=quic
    

    Four connections registered to four edges (QUIC protocol). This is normal. Cloudflare maintains multiple connections to different PoPs for redundancy.


    An unhealthy log — connection terminated errors immediately after startup:


    
    2026-06-02T11:03:14Z ERR failed to serve tunnel connection error="accept stream listener..."
    2026-06-02T11:03:14Z ERR Connection terminated connIndex=1
    

    This usually means cloudflared started before n8n was ready. ./n8nctl restart fixes it — n8n is already up, so the tunnel connects immediately.




    Series: ← Overview | Next: OpenWA Docker Setup →

    Rather have this built for you?

    I set up WhatsApp and n8n automation for small businesses: reply bots, order updates and lead capture, handed over with backups and a known monthly cost. Fixed packages from ₹15,000.

    See packages and pricing

    Also built on WhatsApp: WhatsApp CRM · AI receptionist · lead management · real estate CRM

    Built something similar or want to talk through the architecture? Get in touch.