cloudflare-deployment-guide

Guide for cloudflare-deployment-guide

Cloudflare Tunnel Deployment Guide

For: Legends of Himavat Game Server
Target: 2500 Concurrent Users
Last Updated: 2026-01-05

šŸ“‹ OVERVIEW

This guide covers complete Cloudflare Tunnel setup for production deployment. Complete these steps before deploying the game server.
Prerequisites:
  • Cloudflare account
  • Domain registered with Cloudflare DNS
  • Game server provisioned (see infrastructure-specs.md)
  • SSH access to game server
Estimated Time: 3-4 hours

STEP 1: CLOUDFLARE ACCOUNT SETUP (30 minutes)

1.1 Upgrade to Pro Plan

Cost: $20/month
  1. Log into Cloudflare Dashboard
  2. Select your domain
  3. Navigate to Billing → Subscriptions
  4. Upgrade to Pro Plan
Why Pro?
  • Advanced WAF (Web Application Firewall)
  • Better SSL options
  • 20 Page Rules
  • Improved DDoS protection

1.2 Configure DNS

  1. Go to DNS → Records
  2. Note: We'll add tunnel CNAME later
  3. For now, ensure domain is active on Cloudflare
DNS Settings:
  • Proxy status: Will be enabled (orange cloud)
  • SSL/TLS encryption mode: Full (strict)

STEP 2: INSTALL CLOUDFLARED ON GAME SERVER (30 minutes)

2.1 SSH into Game Server

ssh user@your-game-server-ip

2.2 Download and Install cloudflared

For Ubuntu/Debian:
# Download cloudflared
curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o cloudflared

# Move to system directory
sudo mv cloudflared /usr/local/bin/

# Make executable
sudo chmod +x /usr/local/bin/cloudflared

# Verify installation
cloudflared --version
Expected Output: cloudflared version 2024.x.x

STEP 3: AUTHENTICATE WITH CLOUDFLARE (15 minutes)

3.1 Login to Cloudflare

cloudflared tunnel login
This will:
  1. Open a browser window
  2. Ask you to select your domain
  3. Download a cert to ~/.cloudflared/cert.pem
Important: Keep this cert file secure!

3.2 Verify Authentication

ls -la ~/.cloudflared/
Expected Output: Should see cert.pem file

STEP 4: CREATE TUNNEL (20 minutes)

4.1 Create the Tunnel

cloudflared tunnel create loh-game
Expected Output:
Tunnel credentials written to /home/user/.cloudflared/<TUNNEL-ID>.json
Created tunnel loh-game with id <TUNNEL-ID>
IMPORTANT: Save the <TUNNEL-ID> - you'll need it!

4.2 Verify Tunnel Created

cloudflared tunnel list
Expected Output: Should show loh-game tunnel

STEP 5: CONFIGURE TUNNEL (30 minutes)

5.1 Create Configuration File

sudo mkdir -p /etc/cloudflared
sudo nano /etc/cloudflared/config.yml

5.2 Add Configuration

Replace <TUNNEL-ID> with your actual tunnel ID:
tunnel: <TUNNEL-ID>
credentials-file: /home/user/.cloudflared/<TUNNEL-ID>.json

ingress:
  # WebSocket endpoint for game
  - hostname: game.yourdomain.com
    service: ws://localhost:3000
    originRequest:
      noTLSVerify: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      
  # HTTP endpoint for health checks (optional)
  - hostname: game.yourdomain.com
    path: /health
    service: http://localhost:3000
    
  # Catch-all rule (required)
  - service: http_status:404
Configuration Explained:
  • noTLSVerify: true - Server can use self-signed cert
  • connectTimeout: 30s - Timeout for establishing connections
  • tcpKeepAlive: 30s - Keep connections alive
  • keepAliveConnections: 100 - Connection pool size

5.3 Test Configuration

cloudflared tunnel --config /etc/cloudflared/config.yml ingress validate
Expected Output: Configuration is valid

STEP 6: CONFIGURE DNS (15 minutes)

6.1 Route Traffic to Tunnel

cloudflared tunnel route dns loh-game game.yourdomain.com
Expected Output: Created CNAME record for game.yourdomain.com

6.2 Verify DNS in Cloudflare Dashboard

  1. Go to DNS → Records
  2. Should see CNAME record:
    • Name: game
    • Target: <TUNNEL-ID>.cfargotunnel.com
    • Proxy status: Enabled (orange cloud)

STEP 7: RUN TUNNEL AS SERVICE (45 minutes)

7.1 Create systemd Service File

sudo nano /etc/systemd/system/cloudflared.service

7.2 Add Service Configuration

[Unit]
Description=Cloudflare Tunnel
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/cloudflared tunnel --config /etc/cloudflared/config.yml run loh-game
Restart=on-failure
RestartSec=10s
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

7.3 Enable and Start Service

# Reload systemd
sudo systemctl daemon-reload

# Enable service (start on boot)
sudo systemctl enable cloudflared

# Start service
sudo systemctl start cloudflared

# Check status
sudo systemctl status cloudflared
Expected Output: Active: active (running)

7.4 View Logs

# Follow logs in real-time
sudo journalctl -u cloudflared -f

# View last 100 lines
sudo journalctl -u cloudflared -n 100
Expected Log Output:
Connection <ID> registered
Tunnel <TUNNEL-ID> started

STEP 8: CONFIGURE CLOUDFLARE SECURITY (60 minutes)

8.1 Enable WAF (Web Application Firewall)

  1. Go to Security → WAF
  2. Click Create rule
  3. Add rule for WebSocket protection:
Rule: Block Invalid WebSocket Upgrades
Field: http.request.uri.path
Operator: equals
Value: /ws
AND
Field: http.request.headers["Upgrade"]
Operator: does not equal
Value: websocket
Action: Block

8.2 Configure Rate Limiting

  1. Go to Security → WAF → Rate limiting rules
  2. Click Create rule
Rule 1: Connection Rate Limit
Rule name: Limit Concurrent Connections
If incoming requests match:
  - URI Path equals /ws
  - Connection: Upgrade
When rate exceeds:
  - 10 requests per 10 seconds
  - Counted per IP address
Then:
  - Block for 60 seconds
Rule 2: Global Request Limit
Rule name: Global Rate Limit
If incoming requests match:
  - All incoming requests
When rate exceeds:
  - 100 requests per minute
  - Counted per IP address
Then:
  - Challenge (CAPTCHA)

8.3 Enable Bot Fight Mode

  1. Go to Security → Bots
  2. Enable Bot Fight Mode
  3. Set to Allow verified bots (for monitoring/SEO)

8.4 Configure DDoS Protection

  1. Go to Security → DDoS
  2. Ensure HTTP DDoS Attack Protection is enabled
  3. Sensitivity: Medium (adjust based on traffic patterns)

8.5 SSL/TLS Configuration

  1. Go to SSL/TLS → Overview
  2. Set encryption mode: Full (strict)
    • Cloudflare ↔ Origin: Encrypted with valid cert
  3. Go to Edge Certificates
  4. Enable:
    • Always Use HTTPS: On
    • HTTP Strict Transport Security (HSTS): On
      • Max Age: 6 months
      • Include subdomains: Off
      • Preload: Off
    • Minimum TLS Version: TLS 1.2
    • Opportunistic Encryption: On
    • TLS 1.3: On

STEP 9: CONFIGURE FIREWALL ON GAME SERVER (30 minutes)

CRITICAL: Since Cloudflare Tunnel handles all ingress, block direct access to port 3000.

9.1 Configure iptables/nftables

# Block direct access to port 3000 from internet
sudo iptables -A INPUT -p tcp --dport 3000 -s 0.0.0.0/0 -j DROP

# Allow localhost connections (for tunnel)
sudo iptables -I INPUT -s 127.0.0.1 -p tcp --dport 3000 -j ACCEPT

# Allow SSH (replace YOUR_IP with your actual IP)
sudo iptables -A INPUT -p tcp --dport 22 -s YOUR_IP -j ACCEPT

# Save rules
sudo iptables-save > /etc/iptables/rules.v4

9.2 Verify Firewall

# Check rules
sudo iptables -L -n -v

# Test that port 3000 is not accessible externally
# From your local machine:
curl http://your-server-ip:3000
# Expected: Connection refused or timeout

STEP 10: TESTING & VALIDATION (30 minutes)

10.1 Test WebSocket Connection

From your local machine:
# Install wscat if not already installed
npm install -g wscat

# Test connection
wscat -c wss://game.yourdomain.com/ws
Expected Output:
Connected (press CTRL+C to quit)
>
If you see this, the tunnel is working!

10.2 Test from Game Client

  1. Update loh-game/.env.production:
    GAME_SERVER_URL=wss://game.yourdomain.com/ws
  2. Build and run client:
    cd loh-game
    cargo run --release
  3. Try to connect - should establish WebSocket connection

10.3 Monitor Cloudflare Analytics

  1. Go to Analytics & Logs → Traffic
  2. Should see:
    • Requests coming in
    • WebSocket upgrades
    • No errors (or minimal errors during testing)

STEP 11: MONITORING & MAINTENANCE (Ongoing)

11.1 Check Tunnel Health

# Check tunnel status
sudo systemctl status cloudflared

# View recent logs
sudo journalctl -u cloudflared -n 50

# Monitor connections
cloudflared tunnel info loh-game

11.2 Cloudflare Dashboard Monitoring

Daily Checks:
  1. Analytics → Verify traffic patterns normal
  2. Security Events → Check for blocked attacks
  3. Performance → Monitor latency
Weekly Checks:
  1. Rate Limiting → Adjust rules if needed
  2. WAF → Review blocked requests
  3. SSL/TLS → Verify cert renewal

11.3 Set Up Alerts

  1. Go to Notifications
  2. Create alerts for:
    • DDoS Attack Detected
    • High Error Rate (>5% 5xx errors)
    • SSL Certificate Expiring (30 days before)
    • Rate Limit Triggered (>100 events/hour)

TROUBLESHOOTING

Issue: Tunnel Not Connecting

Symptoms: cloudflared service fails to start
Solutions:
# Check logs
sudo journalctl -u cloudflared -n 100

# Common fixes:
1. Verify tunnel ID in config.yml
2. Check credentials file exists and has correct permissions
   chmod 600 ~/.cloudflared/<TUNNEL-ID>.json
3. Ensure game server is running on port 3000
4. Restart tunnel: sudo systemctl restart cloudflared

Issue: WebSocket Connection Fails

Symptoms: Client can't connect to wss://game.yourdomain.com/ws
Solutions:
  1. Check DNS propagation: dig game.yourdomain.com
  2. Verify CNAME points to tunnel
  3. Check Cloudflare proxy status (orange cloud enabled)
  4. Test with wscat -c wss://game.yourdomain.com/ws
  5. Check WAF rules aren't blocking legitimate traffic

Issue: High Latency

Symptoms: Game feels laggy, >200ms latency
Solutions:
  1. Check Cloudflare datacenter: Use Analytics → Performance
  2. Verify server location is optimal (close to users)
  3. Adjust tunnel keepAlive settings in config.yml
  4. Consider Cloudflare Argo (paid, reduces latency)

Issue: Rate Limiting Too Aggressive

Symptoms: Legitimate users getting blocked
Solutions:
  1. Review Security → Events
  2. Adjust rate limiting rules:
    • Increase thresholds
    • Change from "Block" to "Challenge"
  3. Whitelist specific IPs if corporate/testing traffic

COST BREAKDOWN

ItemMonthly Cost
Cloudflare Pro Plan$20
Cloudflare Tunnel$0 (included)
DDoS Protection$0 (included)
WAF (20 rules)$0 (included with Pro)
Rate Limiting$0 (included with Pro)
TOTAL$20/month
Optional Add-ons:
  • Argo Smart Routing: $5 base + $0.10/GB (reduces latency ~30%)
  • Load Balancing: $5/month (for multiple servers)
  • Advanced Rate Limiting: $5/month (for >10 rules)

SECURITY BEST PRACTICES

āœ… Do:
  • Use noTLSVerify: true only for development/self-signed certs
  • Enable HSTS (HTTP Strict Transport Security)
  • Set minimum TLS 1.2
  • Use Bot Fight Mode
  • Monitor rate limit events
  • Keep cloudflared updated
āŒ Don't:
  • Expose port 3000 directly to internet
  • Use same tunnel for dev/staging/prod
  • Disable Cloudflare proxy (orange cloud)
  • Ignore security alerts
  • Use weak rate limits on production

ROLLBACK PROCEDURE

If you need to disable the tunnel and revert:

Quick Rollback

# Stop tunnel
sudo systemctl stop cloudflared
sudo systemctl disable cloudflared

# Remove DNS record from Cloudflare Dashboard
# Delete CNAME for game.yourdomain.com

# Re-expose port 3000 directly (temporary)
sudo iptables -D INPUT -p tcp --dport 3000 -s 0.0.0.0/0 -j DROP

Full Cleanup

# Delete tunnel
cloudflared tunnel delete loh-game

# Remove config
sudo rm /etc/cloudflared/config.yml
sudo rm /etc/systemd/system/cloudflared.service

# Remove credentials
rm ~/.cloudflared/<TUNNEL-ID>.json

# Reload systemd
sudo systemctl daemon-reload

SUCCESS CHECKLIST

Before marking this guide complete:
  • Cloudflare Pro plan active
  • cloudflared installed and running as service
  • Tunnel created and configured
  • DNS CNAME record pointing to tunnel
  • WAF rules configured
  • Rate limiting enabled
  • Bot Fight Mode enabled
  • SSL/TLS set to Full (strict)
  • Port 3000 blocked from direct access
  • WebSocket connection tested successfully
  • Game client connects via wss://
  • Monitoring and alerts configured
  • Documentation updated with actual domain/tunnel ID

NEXT STEPS

After completing Cloudflare setup:
  1. āœ… Return to consolidated_tasks.md → Agent 1, Phase 2 (mark Cloudflare tasks complete)
  2. āœ… Continue with Phase 3: Observability & Monitoring
  3. āœ… Update .env.production with actual GAME_SERVER_URL
  4. āœ… Begin staged rollout (100 → 500 → 1500 → 2500 users)
Reference Files:
  • infrastructure-specs.md - Server specifications
  • security-infrastructure-todo.md - Full deployment checklist
  • parallel-workstream-breakdown.md - Agent 1 tasks

Document Version: 1.0
Last Tested: 2026-01-05
Cloudflare Version: cloudflared 2024.x.x