How to use Cloudflare and Raspberry Pi Together
Below is a detailed, technical, and (roughly) 5,000-word exploration of how one can integrate Cloudflare and Raspberry Pi — covering motivations, architecture, configuration, advanced options, trade-offs, security, monitoring, and future directions. Use this as a foundation for a white paper, blog, or internal reference.
From Chat GPT
Key benefits include:
In this paper, we’ll focus largely on the HTTP(s) + reverse proxy + TCP fallback scenario, and then extend to more advanced patterns.
5. Installing & Configuring
For example, on a Debian-based Pi:
Alternatively, download a pre-built binary (e.g.
5.2 (Optional) Creating a
For security (not running as root), you may create a dedicated user:
Then you can run the service under that user. (Some tutorials for Pi-hole / DNS use this model) (tips.dchakro.com)
You’ll see commands such as
This command opens (or provides) a URL to visit and authenticate with Cloudflare. After successful login, a certificate (e.g.
This generates tunnel credentials, e.g. a JSON file in
This means when requests come via Cloudflare to
You can also use
This instructs Cloudflare to create a CNAME record pointing your hostname to the tunnel’s endpoint. (Pi My Life Up)
In Cloudflare’s DNS tab, you should see a CNAME entry (e.g.
Or install it as a systemd service so that it starts on boot:
This ensures the tunnel is persistent across reboots. (Pi My Life Up)
This means
Cloudflare can issue and manage Origin Certificates, which you install on your Pi and configure Nginx (or your web server) to use. This way, the traffic between Cloudflare and your Pi is encrypted and trusted. (But note: Cloudflare does not need to validate that TLS certificate publicly — it’s internal). Some guides walk through switching from Cloudflare origin certs to Let’s Encrypt. (Ladvien's Lab)
Create server blocks, such as
Then enable:
This configuration lets Nginx handle routing from a single port (e.g. 80) addressed by multiple hostnames or paths. The tunnel ingress maps to Nginx, and Nginx further routes.
In use:
This way, SSH over port 22 is tunnelled via Cloudflare and forwarded to your Pi. However:
If your backend (e.g. SSH daemon, custom TCP app) doesn’t support PROXY protocol, it may misidentify the client.
If one fails or disconnects, another can take over traffic. This helps minimize downtime.
A guide describes running replicas on multiple Pis and letting them serve the same ingress rules. (Medium)
This allows Cloudflare to distribute or fallback if one origin is down.
Also monitor CPU, memory, and network health of the Pi itself.
11.7 Protecting the
12.1
16.1 Sample
Then reload:
Then your ingress mapping uses
In
And ensure you accept connections over the port mapped. Then the SSH server sees the real client IP.
Clients connect like:
(assuming Cloudflare forwarded port 443 for SSH mapping).
If you like, I can generate a ready-to-publish version of this article (with formatting, diagrams, and references), or build a working sample repo that demonstrates a Pi + Cloudflare setup step by step. Do you want me to do that next?
Below is a detailed, technical, and (roughly) 5,000-word exploration of how one can integrate Cloudflare and Raspberry Pi — covering motivations, architecture, configuration, advanced options, trade-offs, security, monitoring, and future directions. Use this as a foundation for a white paper, blog, or internal reference.
From Chat GPT
Table of Contents
- Introduction & Motivation
- Architectural Patterns & Use Cases
- Core Components & Terminology
- Setting Up a Raspberry Pi Environment
- Installing & Configuring
cloudflaredon Raspberry Pi - Creating & Managing Cloudflare Tunnels
- DNS, Routing, and Ingress Rules
- Reverse Proxy / Web Server Integration (e.g. Nginx)
- Handling TCP/UDP Services (Spectrum, Proxy Protocol)
- High Availability & Redundancy
- Security Considerations
- Monitoring, Logging, and Diagnostics
- Performance / Latency / Caching
- Limitations, Costs, and Trade-offs
- Advanced Topics, Extensions, and Future Work
- Sample Configurations & Code Snippets
- Conclusion
1. Introduction & Motivation
1.1 The challenge of exposing a home/edge device to the Internet
A Raspberry Pi (or a cluster of Pis) can host web services, media servers, IoT gateways, home automation APIs, and more. But exposing those services publicly is nontrivial:- Many ISPs use dynamic IPs, so your public IP may change.
- Some ISPs even place customers behind Carrier-Grade NAT (CGNAT), making port forwarding impossible.
- Opening ports on your home router or firewall increases attack surface.
- Maintaining HTTPS, handling DDoS, TLS termination, and resilience adds operational burden.
1.2 Why Cloudflare helps
Cloudflare offers a global network, reverse-proxying, DDoS protection, TLS, and tunneling mechanisms (viacloudflared) that allow you to connect your origin (Raspberry Pi) to the Cloudflare network without exposing it directly.Key benefits include:
- You don’t need to forward ports or open firewall holes on your router.
- Your origin’s IP address remains hidden behind Cloudflare.
- You can use Cloudflare’s TLS, caching, and firewalling capabilities.
- For non-HTTP services, Cloudflare offers Spectrum (for TCP/UDP) and proxy protocol support. (Cloudflare)
- You can build redundancy (multi-hop tunnels, replicas) to reduce single points of failure. (Medium)
- Cloudflare’s Zero Trust / Access features allow you to gate access via identities, not just network. (E.g. SSH over a browser) — Cloudflare blogs show such use with Pi. (The Cloudflare Blog)
2. Architectural Patterns & Use Cases
Here are common patterns when integrating Cloudflare and Raspberry Pi:| Pattern | Description | Use Cases |
|---|---|---|
| HTTP(s) web app via Tunnel | Use cloudflared to expose local web server (e.g. Nginx, Flask, Node.js) over a tunnel. | Personal websites, dashboards, IoT front ends |
| Multi-service ingress / reverse proxy | Use a Pi as a reverse proxy (e.g. Nginx) and route multiple hostnames / paths. Tunnel connects this to Cloudflare. | Hosting multiple microservices, home labs |
| TCP/UDP services via Spectrum | Use Cloudflare Spectrum to front non-HTTP protocols (SSH, RDP, MQTT, game servers) and route them to Pi. | Remote SSH, MQTT broker, game servers |
| Hybrid edge + central backend | Pi handles low-latency tasks locally; Cloudflare handles routing and fallback to central servers. | IoT device aggregation with fallback |
| High-availability / multi-Pi failover | Use replica tunnels or redundant Pi nodes to provide failover ingress. (Medium) | Critical services wanting uptime |
3. Core Components & Terminology
Before diving into setup, let’s clarify the principal components and vocabulary.- Origin: The Raspberry Pi instance (or service) that you want to expose.
- Edge / Cloudflare Network: Cloudflare's globally distributed servers that accept incoming client traffic.
- cloudflared: The lightweight daemon that runs on the origin, opens a persistent secure tunnel to Cloudflare, and handles ingress routing.
- Tunnel: The secure, encrypted channel from the origin to Cloudflare.
- Ingress rules: Rules in the
config.yml(or via dashboard) that determine how hostname / path requests map to local services. - DNS / CNAME / Records: In the Cloudflare dashboard, you map your domain names to the tunnel endpoint.
- Spectrum: Cloudflare’s L4 proxy solution that allows TCP/UDP services to be proxied via Cloudflare. (Cloudflare)
- Proxy Protocol: A protocol by which Cloudflare can annotate the original client’s IP in a TCP connection passed to the origin — used when your service needs to know the source IP. (Cloudflare Docs)
- Replica / High-Availability Tunnel: Additional tunnels or nodes that can take over if the primary fails. (Medium)
- Zero Trust / Access / Gateway (Optional): Cloudflare’s enterprise features to enforce identity-based access or filtering in front of your services.
4. Setting Up a Raspberry Pi Environment
Before installing Cloudflare components, your Pi should be running a stable Linux OS (Raspberry Pi OS, Ubuntu, etc.) and set up with network connectivity. Key initial steps:- Update and upgrade OS packages
Code:sudo apt update && sudo apt upgrade -y- If your Pi is on Wi-Fi or Ethernet, it helps to assign a static or reserved lease so it doesn’t change.
- This is important for internal routing (Nginx, reverse proxy) later.
- Install basic utilities
These are needed for adding repositories, fetching packages, etc.Code:sudo apt install curl lsb-release- For example, install Nginx (
sudo apt install nginx), or deploy a Flask/Node/ASP.NET app, etc. - Ensure it is accessible locally (e.g.
curl http://localhost:80) before exposing externally.
- For example, install Nginx (
5. Installing & Configuring cloudflared on Raspberry Pi
cloudflared is the core agent that establishes a secure tunnel to Cloudflare. Installing it on a Raspberry Pi is straightforward.5.1 Download / install cloudflared binary
Cloudflare provides official binaries and repositories. (Cloudflare Docs)For example, on a Debian-based Pi:
Code:
# Add GPG key
curl -L https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-archive-keyring.gpg >/dev/null
# Add the repository
echo "deb [signed-by=/usr/share/keyrings/cloudflare-archive-keyring.gpg] https://pkg.cloudflare.com/cloudflared $(lsb_release -cs) main" \
| sudo tee /etc/apt/sources.list.d/cloudflared.list
# Update and install
sudo apt update
sudo apt install cloudflared
cloudflared-linux-arm or cloudflared-linux-arm64) and place it in /usr/local/bin, mark executable. (tips.dchakro.com)
Code:
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm
sudo mv cloudflared-linux-arm /usr/local/bin/cloudflared
sudo chmod +x /usr/local/bin/cloudflared
cloudflared version
Note: On Pi Zero or older ARM architectures, you may need a specific build. Some users encountered mismatches of armhf vs arm64. (Reddit)
5.2 (Optional) Creating a cloudflared user
For security (not running as root), you may create a dedicated user:
Code:
sudo useradd -s /usr/sbin/nologin -r -M cloudflared
5.3 Basic invocation & help
Once installed:
Code:
cloudflared --help
tunnel, login, run, service install, etc.6. Creating & Managing Cloudflare Tunnels
Oncecloudflared is installed, you’ll set up a tunnel and map hostnames to local services.6.1 Authenticate / login
Code:
cloudflared tunnel login
cert.pem) is stored in ~/.cloudflared/ to allow the agent to register tunnels. (Pi My Life Up)6.2 Create a named tunnel
Code:
cloudflared tunnel create my-pi-tunnel
~/.cloudflared/1234-uuid.json. It also prints the tunnel ID.6.3 Configure ingress (routing)
Create a configuration file (e.g.config.yml) under ~/.cloudflared/:
Code:
tunnel: <TUNNEL_ID>
credentials-file: /home/pi/.cloudflared/<TUNNEL_ID>.json
ingress:
- hostname: example.yourdomain.com
service: http://localhost:80
- hostname: api.yourdomain.com
service: http://localhost:8080
- service: http_status:404
example.yourdomain.com, they’ll be forwarded to localhost:80 on your Pi. Additional rules can route to other services or ports.You can also use
https://… or tcp://… or ssh://… (depending on your use). (Pi My Life Up)6.4 Route DNS to the tunnel
Use Cloudflare’s dashboard (Zero Trust / Tunnels UI) or via CLI:
Code:
cloudflared tunnel route dns my-pi-tunnel example.yourdomain.com
In Cloudflare’s DNS tab, you should see a CNAME entry (e.g.
example -> tunnelUUID.cfargotunnel.com). You must ensure your domain is using Cloudflare’s nameservers.6.5 Running the tunnel
You can run the tunnel manually:
Code:
cloudflared tunnel run my-pi-tunnel
Code:
sudo cloudflared --config ~/.cloudflared/config.yml service install
sudo systemctl enable cloudflared
sudo systemctl start cloudflared
7. DNS, Routing, and Ingress Rules
The ingress rules in yourconfig.yml map hostnames (and optionally path matches) to local backend services. This is flexible.7.1 Ingress precedence & fallback
The rules are evaluated in order. If none match, the final rule (likehttp_status:404) catches unmatched requests. You can also route unmatched traffic to default services.7.2 Multiple hostnames, path-based routing
You can do this:
Code:
ingress:
- hostname: app.yourdomain.com
service: http://localhost:3000
- hostname: app.yourdomain.com
path: /api/*
service: http://localhost:5000
- service: http_status:404
api paths go to backend 5000, while other paths go to port 3000.7.3 TLS / HTTPS handling
By default, Cloudflare handles TLS termination at the edge. Connections are decrypted at Cloudflare, and forwarded over the tunnel (possibly in plaintext, unless you configure origin TLS). You can also configure origin TLS (i.e. use TLS between Cloudflare and your Pi) to ensure end-to-end encryption.Cloudflare can issue and manage Origin Certificates, which you install on your Pi and configure Nginx (or your web server) to use. This way, the traffic between Cloudflare and your Pi is encrypted and trusted. (But note: Cloudflare does not need to validate that TLS certificate publicly — it’s internal). Some guides walk through switching from Cloudflare origin certs to Let’s Encrypt. (Ladvien's Lab)
7.4 Path-based rewrites, header manipulation, and access policies
You can add more sophistication:- Rewrite or strip path prefixes.
- Add or override headers (e.g.
X-Forwarded-For,X-Real-IP). - Require authentication (via Cloudflare Access) before forwarding to certain hostnames or paths (this is a Zero Trust feature).
- Block or filter requests (using Cloudflare WAF, firewall rules, rate limits).
8. Reverse Proxy / Web Server Integration (e.g. Nginx)
Often, one wants the Pi to host multiple services (web, API, dashboards), so a local reverse proxy (e.g. Nginx) is useful to co-locate these. The tunnel points to Nginx, which then further proxies to the appropriate backend.8.1 Basic Nginx setup
Install Nginx:
Code:
sudo apt install nginx
/etc/nginx/sites-available/app.conf:
Code:
server {
listen 127.0.0.1:80; # only local
server_name example.yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /api/ {
proxy_pass http://localhost:5000/;
...
}
}
Code:
sudo ln -s /etc/nginx/sites-available/app.conf /etc/nginx/sites-enabled/
sudo systemctl reload nginx
8.2 Why keep Nginx, given Cloudflare already proxies?
You might ask: if Cloudflare is already proxying traffic, do I still need Nginx? Yes, because:- You often have multiple backend services — Nginx acts as local aggregator.
- You may want features like caching, compression, URL rewriting, static assets, or path-level handling.
- Some services expect to run on typical web ports.
- Cloudflare cannot (via tunnel) route to multiple local services with path-level logic (ingress rules do some of that, but Nginx may give more flexibility, custom modules, etc).
8.3 Integrating with origin TLS
If you choose to use TLS between Cloudflare and your Pi:- Acquire or generate a certificate (e.g. origin cert from Cloudflare or Let’s Encrypt).
- Configure Nginx to listen on
127.0.0.1:443with that cert. - In your
config.yml, change the ingress mapping toservice: https://127.0.0.1:443.
9. Handling TCP/UDP Services (Spectrum & Proxy Protocol)
If you have non-HTTP services (SSH, MQTT, games, custom TCP/UDP apps), you can also expose them via Cloudflare via Spectrum or tunnel + TCP routing.9.1 Spectrum: Cloudflare’s TCP/UDP proxy
Cloudflare Spectrum is their layer-4 proxy, allowing you to front arbitrary TCP or UDP services. (Cloudflare)In use:
- You configure a Spectrum application in Cloudflare dashboard, specifying the protocol (TCP or UDP), port(s), and origin addresses.
- You can enable Proxy Protocol v1 or v2 so that Cloudflare attaches the client IP metadata when forwarding to the origin. (Cloudflare Docs)
- For example, you can proxy SSH (TCP 22) or MQTT (TCP 1883) through Cloudflare.
- Spectrum is a paid / enterprise-level feature (not always available on free plans). (Cloudflare Community)
- You’ll need to ensure your Pi is reachable over that port internally or via the tunnel.
9.2 Exposing TCP via tunnel ingress
cloudflared now supports tcp:// in ingress rules, so you can map a TCP port to a service on the Pi. For example:
Code:
ingress:
- hostname: ssh.yourdomain.com
service: ssh://localhost:22
- service: http_status:404
- The client typically connects to a Cloudflare edge, which picks the correct destination.
- You should enable Proxy Protocol if your SSH server requires the real client IP (rather than Cloudflare’s IP).
- Not all protocols (especially UDP) may be supported via tunnel ingress directly; Spectrum may still be necessary.
- If your service expects to know the remote IP or connection metadata, you need to configure your server to accept Proxy Protocol or to unwrap it.
9.3 Proxy Protocol and real client IPs
When traffic is proxied (especially for TCP), the origin server sometimes sees Cloudflare’s IP as client unless Proxy Protocol is used. The PROXY protocol version 1 (human readable) or v2 (binary) allows Cloudflare to prepend a header including the original TCP address, so your backend can parse it and extract the real client IP. (Cloudflare Docs)If your backend (e.g. SSH daemon, custom TCP app) doesn’t support PROXY protocol, it may misidentify the client.
9.4 Example: SSH via tunnel
- In
config.yml:
Code:ingress: - hostname: ssh.yourdomain.com service: ssh://localhost:22 - service: http_status:404 - In Cloudflare Dashboard, ensure the
ssh.yourdomain.comentry is CNAME’d to the tunnel. - On your SSH server, enable Proxy Protocol support (if available) so it can read the actual client IP.
- Clients connect via
ssh [email protected] -p 443(or whatever port is proxied).
10. High Availability & Redundancy
One risk in a single Pi + tunnel setup is that ifcloudflared or the Pi fails, your service is unreachable. To mitigate this, you can design for redundancy.10.1 Replica tunnels / failover
Cloudflare supports tunnel replicas, meaning multiplecloudflared agents (e.g. on separate Pis or VMs) can be configured against the same tunnel, providing failover. (Medium)If one fails or disconnects, another can take over traffic. This helps minimize downtime.
A guide describes running replicas on multiple Pis and letting them serve the same ingress rules. (Medium)
10.2 Load balancing multiple origins
In your ingress or load balancing settings, you can configure multiple origin endpoints (e.g. multiple Pi nodes) for a given hostname, with health checks and failover routing.This allows Cloudflare to distribute or fallback if one origin is down.
10.3 Monitoring & watchdogs
Ensure thatcloudflared service is monitored and restarted automatically. Use systemd’s auto-restart flags, or external watchdog processes.Also monitor CPU, memory, and network health of the Pi itself.
10.4 Avoiding single point of failure
- Use at least two Pis (or fallback system) running replica tunnels.
- Use external health-checking (Cloudflare Load Balancer).
- Regular backups of configurations, and automated scripts to restore tunnel configs.
11. Security Considerations
When exposing any device to the Internet, security is paramount. Here are best practices and traps to avoid.11.1 Minimize exposure surface
- Don’t open arbitrary ports on your router — rely on the tunnel instead.
- Only expose the services you intend (via ingress rules or firewall).
- Use IP or access-based firewalling (Cloudflare firewall rules, Pi firewall).
11.2 Use TLS end-to-end
- Even if Cloudflare handles TLS, use origin TLS to encrypt traffic inside the tunnel.
- Use strong cipher suites and TLS configurations.
- Use Cloudflare origin certificates or trusted CA certs locally.
11.3 Authenticate sensitive routes
- Use Cloudflare Access or Zero Trust policies to gate sensitive hostnames (e.g. SSH panel, admin UI).
- Require identity (OAuth, SSO) before allowing connections.
11.4 Validate and sanitize inputs
- You’re still running a web service. Ensure your app is secure (avoid SQL injection, XSS, etc).
- Monitor logs for suspicious activity.
11.5 Use least-privilege on the Pi
- Run services under non-root users.
- Use containerization or isolation if possible (e.g. Docker).
- Keep software and OS updated with security patches.
11.6 Limit Cloudflare-origin access
- Configure your Pi’s firewall (iptables, ufw) to accept connections only from Cloudflare IP ranges.
- Deny connections from elsewhere to ports 80/443/other origin ports.
- Periodically update the IP ranges list (Cloudflare publishes it).
11.7 Protecting the cloudflared credentials
- The JSON credentials file should be stored securely (readable only by the
cloudflareduser). - In the event of compromise, you can revoke and recreate the tunnel credentials.
11.8 Rate limiting, brute-force protection
- Use Cloudflare’s WAF and rate-limiting features on ingress.
- Employ 2FA where applicable (admin UIs, dashboards, SSH).
12. Monitoring, Logging, and Diagnostics
To maintain reliability and respond to failures, you need observability.12.1 cloudflared logs & metrics
cloudflaredwrites logs about connection status, health, ingress routing, errors.- Use
journalctl -u cloudflaredor log file paths. - Enable verbose logging for debugging (temporarily).
- For metrics (e.g. connection count, latency), you can integrate with Prometheus using the
metricsflag (if supported in your version).
12.2 Application & web server logs
- Nginx, your app, etc. continue to log request/response, errors.
- Configure logs in JSON or structured format for easier aggregation.
12.3 Cloudflare (Edge) analytics
- In Cloudflare dashboard, monitor request counts, latency, errors, firewall events.
- Use Cloudflare’s logging (Enterprise feature) to export edge logs to your SIEM.
12.4 Health checks and alerts
- Deploy external uptime monitors (e.g. Pingdom, UptimeRobot) to check your public domain.
- Use alerting (email, Slack) on downtime or error thresholds.
12.5 Diagnosing failures
Common failure modes:cloudflareddisconnected or crashed — check logs, restart service.- DNS misconfiguration (CNAME not pointing to tunnel) — validate DNS record.
- Ingress mapping error (hostname mismatch) — confirm ingress and
config.yml. - Local service unreachable (e.g. Nginx down) — test
curl localhost. - Certificate / TLS errors — check your certs.
13. Performance, Latency & Caching
Using a tunnel and passing traffic via Cloudflare adds some overhead but has benefits.13.1 Latency & routing overhead
- Client → Cloudflare edge → Tunnel → Pi → service, then back. There's an extra hop.
- Choose Cloudflare data centers close to your users to reduce latency.
- Monitor round-trip times and end-to-end latency.
13.2 Caching & CDN benefits
- For HTTP(s) content, Cloudflare's caching and CDN features reduce load on your Pi.
- Static content (images, JS, CSS) can be cached at edges, fewer requests hit the Pi.
- Use Cloudflare Cache Rules (Page Rules, Cache-Control headers) to optimize.
13.3 Connection multiplexing & reuse
cloudflaredcan multiplex multiple requests over a single connection to the Pi, reducing overhead.- Ensure keepalive settings and HTTP/2 are optimized in your app and Nginx.
13.4 Load capacity & throughput
- The Pi’s network interface and CPU are constraints — keep expected traffic volume in mind.
- Monitor resource usage (CPU, RAM, network bandwidth).
- Offload heavy processing (e.g. image resizing) to more powerful backend if necessary.
13.5 Scalability strategies
- Use multiple Pi nodes (load-balanced origins).
- Use more powerful hardware (or edge nodes) for high traffic.
- Push caching or static assets to Cloudflare edges as much as possible.
14. Limitations, Costs, and Trade-offs
No system is without trade-offs. Be aware of:14.1 Feature / plan restrictions
- Some Cloudflare features (Spectrum, enterprise logging, advanced firewall, access policies) are only available on paid/enterprise plans. (Cloudflare Community)
- Tunnel replicas or high-availability features may have quotas or limitations. (Medium)
14.2 Tunnel as a single point of failure
- If
cloudflaredcrashes or the Pi fails, traffic is lost unless redundancy is built.
14.3 Increased complexity
- More moving parts (DNS, tunnel, reverse proxy) means more failure modes and more maintenance overhead.
- You have to manage TLS, ingress rules, configuration syncs, etc.
14.4 Latency overhead
- The tunnel adds an extra hop, which may affect latency-sensitive apps, especially if the path to Cloudflare’s edge is non-optimal.
14.5 Pi resource constraints
- The Pi is modest in CPU, memory, and network throughput. High-traffic scenarios may overwhelm it.
- It may not be ideal as a production-grade high-throughput server.
14.6 IP rotation / blacklisting
- If your Pi’s IP changes internally (DHCP) and you haven’t reserved it, mapping can break.
- If your origin IP becomes blacklisted, you may need to rotate and reconfigure firewall rules.
14.7 Vendor lock-in mindset
- Relying heavily on Cloudflare’s edge features may make migration harder in future.
15. Advanced Topics, Extensions, and Future Work
Here are some more advanced or forward-looking ideas you can build on.15.1 Hybrid edge + central cloud
You can route certain traffic locally (low latency) and fallback to cloud-based services if Pi is down. Use conditional routing or health-based routing in Cloudflare.15.2 Edge functions / Workers on Cloudflare
Use Cloudflare Workers to preprocess or transform requests before they hit your Pi – e.g. caching logic, A/B tests, authentication, response adjustments.15.3 IoT / MQTT routing with TLS
Host an MQTT broker or other IoT backend on Pi and expose via Cloudflare (e.g. via tunnel/tcp). Use TLS + client certificates for security.15.4 Zero Trust Identity & Access
Use Cloudflare Access (Zero Trust) to gate connections to SSH, admin panels, APIs. Only authenticated users can pass through. Combine with short-lived tokens.15.5 Multi-region Pis with Global Load Balancer
If you have Pis in multiple locations, use Cloudflare Load Balancer with geo-based routing + health checks to send clients to the closest or healthy origin.15.6 Autoscaling & ephemeral origins
You could have Pis spin up or down (for instance in a cluster) and dynamically register tunnels. Useful for dynamic lab or edge computing workloads.15.7 Custom metrics & observability
Extendcloudflared metrics, feed into Prometheus / Grafana dashboards. Use site-wide tracing (e.g. OpenTelemetry) across Cloudflare + Pi.15.8 Alternative tunneling / bastion approaches
Compare Cloudflare with alternatives like Tailscale, WireGuard, or VPN-based reverse tunneling, and possibly build hybrid systems. (But Cloudflare offers integrated edge features and DDoS protection that VPNs don’t provide natively.)16. Sample Configurations & Code Snippets
Here are sample configuration files and code snippets you can adapt.16.1 Sample config.yml for cloudflared
Code:
tunnel: 12345678-90ab-cdef-1234-567890abcdef
credentials-file: /home/pi/.cloudflared/12345678-90ab-cdef-1234-567890abcdef.json
ingress:
- hostname: www.yourdomain.com
service: https://localhost:443
- hostname: api.yourdomain.com
service: http://localhost:5000
- hostname: ssh.yourdomain.com
service: ssh://localhost:22
- service: http_status:404
16.2 Systemd service override (if needed)
If you want to override or customize, create/etc/systemd/system/cloudflared.service.d/override.conf:
Code:
[Service]
User=cloudflared
Restart=on-failure
RestartSec=5s
Code:
sudo systemctl daemon-reload
sudo systemctl enable cloudflared
sudo systemctl start cloudflared
16.3 Nginx reverse proxy with SSL
Assuming you use origin TLS with a Cloudflare origin cert:
Code:
server {
listen 127.0.0.1:443 ssl;
server_name www.yourdomain.com;
ssl_certificate /etc/ssl/certs/cf-origin.crt;
ssl_certificate_key /etc/ssl/private/cf-origin.key;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
https://localhost:443.16.4 SSH server config with Proxy Protocol (OpenSSH example)
If your SSH daemon supports ProxyProtocol (recent OpenSSH versions), you can enable:In
/etc/ssh/sshd_config:
Code:
UseProxyProtocol yes
Clients connect like:
Code:
ssh [email protected] -p 443
17. Conclusion
Using Cloudflare and Raspberry Pi together enables you to securely and flexibly expose edge services without breaking your network security posture. The combination gives you:- Simplified exposure (no port forwarding, no static IP required)
- DDoS protection, TLS, and firewalling at the edge
- Fine-grained routing and ingress rules
- Capability to handle non-HTTP services (via Spectrum or tunnel TCP)
- Extensibility with redundancy, load balancing, and access policies
If you like, I can generate a ready-to-publish version of this article (with formatting, diagrams, and references), or build a working sample repo that demonstrates a Pi + Cloudflare setup step by step. Do you want me to do that next?