Deploy a Gunicorn application using a Cloudflare tunnel
I have a small mini PC at home with Linux installed, and I have always wondered how to host my websites on this PC.
I once tried to point the DNS A record directly to the public IP address of my Mini PC. It did not work. The problem had to do with my internet provider not allowing port forwarding. Or something like that (I am not a network expert).
Luckily, Cloudflare was there for me when I checked out their Cloudflare tunnels service.
In this article, I will detail how you can do the same.
What is a Cloudflare Tunnel?
The Cloudflare Tunnel is an outbound connection between your resources and Cloudflare’s global network. Tunnels are persistent objects that route traffic to DNS records.
This service provides a secure way to connect your resources to Cloudflare without a public IP address. With the Tunnel, you do not send traffic to an external IP — instead, a lightweight daemon in your infrastructure (cloudflared) creates outbound-only connections to Cloudflare’s global network.
Image Source: Cloudflare Tunnel Docs
Set up a Cloudflare account and domain
First, you need an account. So, visit Cloudflare and sign up.
Then add your site in Cloudflare Dashboard.
After entering your domain, you need to select a plan. You can choose the free plan, which is enough for what we are trying to do.
And complete the site registration just by adding the Cloudflare Nameservers in your domain Registrar.
The instructions in the image should be clear. But if you have issues, contact me. I can help you.
When done, the domain registration in Cloudflare can take some minutes or hours. So, meanwhile, you can create the tunnel.
Go to the Zero Trust Overview. And click on Access > Tunnels.
Once there, create your first tunnel. Click on + Create a tunnel. Then enter the name. It does not matter which one, it should be a helpful name for yourself.
Then proceed with installing the Tunnel connector in your machine by selecting first your operating system.
This will install a service with a token in your PC.
Check if your tunnel is active. Once it is active, you can now connect your domains
Finally, you can add a public hostname in the tunnel and point it out to your gunicorn UNIX sock file (/run/gunicorn.sock).
In case your gunicorn is bind with a localhost and a port. For instance,
gunicorn <--args> --bind 127.0.0.1:8000, you can select the http Service type in the hostname.