Cloudflare tunnels in Python

Cloudflare tunnels in Python
Photo by Patrick Wittke / Unsplash

Cloudflare provides a way to proxy traffic from the Cloudflare network to your origin servers, for more information see: https://github.com/cloudflare/cloudflared

Instead of using the cloudflared binary directly to set up the tunnel i decided to use the Cloudflare API.

Some example python code to use the Cloudflare v4 API to:

  1. Create a Cloudflare tunnel
  2. Route traffic to the tunnel via CNAME
  3. Show the tunnel token

And finally, connect your origin server to the tunnel with 'cloudflared' binary.

This code creates the tunnel and associated CNAME to the tunnel, prints out your TUNNEL_TOKEN that can be used with the 'cloudflared daemon' to connect your origin server.

When you have the $TUNNEL_TOKEN you can start proxy traffic to your server via Cloudflare with:

cloudflared tunnel run --url http://localhost:8000 --token $TUNNEL_TOKEN

origin server in this case is http://localhost:8000

or with docker-compose:

version: '3'

services:
  cloudflared_example:
    image: cloudflare/cloudflared
    container_name: example
    restart: unless-stopped
    command: tunnel run --url http://example_container:8000
    environment:
      - TZ=Europe/Stockholm
      - TUNNEL_TOKEN=$TUNNEL_TOKEN
  
  example_container:
    restart: unless-stopped
    image: nginx
    container_name: nginx

here the origin server will be example_container

Your application on http://localhost:8000 that is publicly reachable from https://demoapp.example.com is now being served by Cloudflare global CDN and will speed up delivery by using the edge servers closest to you, and as you will get the normal WAF and DDOS protection functionality provided by Cloudflare.

By using multiple cloudflared instances you can now provide high-availability and zero-downtime upgrades to your application.

See the below diagram for the traffic flow between Cloudflare and your origin server that hosts your application:

Sequence diagram for request behind tunnel

This could be used to easily demo an application or to create multiple environments hosted for testing, staging and production.