Use Cloudflare Tunnel to expose your local web server via HTTPS
There are many tools that allow you to expose your local web server to the Internet. Cloudflare also has a service named Tunnel. I use Cloudflare as a domain registrar, DNS provider, web hosting, image storage, etc., so why not use it for development purposes?
Cloudflare Tunnel provides you with a secure way to connect your resources to Cloudflare without a publicly routable IP address. With 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 edge. Cloudflare Tunnel can connect HTTP web servers, SSH servers, remote desktops, and other protocols safely to Cloudflare. This way, your origins can serve traffic through Cloudflare without being vulnerable to attacks that bypass Cloudflare.
Using the Tunnel, we can:
- expose our local web server to the Internet
- use a custom domain name (static)
- use HTTPS
Naturally, it has numerous other functions that I won’t describe here.
Let’s see how to do it. I’m going to use CLI to set up the tunnel, but you can achieve the same using the web dashboard.
We need to install Cloudflared. I use MacOS, so I’m going to install the CLI using Homebrew.
brew install cloudflare/cloudflare/cloudflared
Next, let’s authenticate to Cloudflare, generate a certificate, and select a domain.
cloudflared tunnel login
It’s time to create a tunnel. Let’s say we want to name it localhost
. (You know, because we want to expose our local server!) This command will print the tunnel ID, which we need to set up the tunnel.
cloudflared tunnel create localhost
Create ~/.cloudflared/config.yml
file, and add the following content:
url: http://localhost:8000
tunnel: <TUNNEL-ID>
credentials-file: /Users/<user>/.cloudflared/<TUNNEL-ID>.json
Replace <TUNNEL-ID>
with the ID of the tunnel you created in the previous step, http://localhost:8000
with the URL of your local web server, and <user>
with your system username.
Let’s say you have selected example.com
during the login step and want to use localhost.example.com
as a tunnel address.
cloudflared tunnel route dns localhost localhost.example.com
The last step is to run the tunnel.
cloudflared tunnel run
That’s it. You can now access your local web server using the tunnel address, https://localhost.example.com
.
You can read more about Cloudflare Tunnel here.