Using Cloudflare Tunnels to Expose Local Containers
Use Cloudflare Tunnels to expose local containers to the internet.
Cloudflare Access has a free tier that will allow us to create tunnels from our own network into Cloudflare's network. This can be an effective workaround for CG-NAT or for those who simply do not want to open ports on their network.
Getting Started
For the initial setup, the domain used must be active in a Cloudflare account that you can manage.
If you do not already have a Cloudflare account or your domain is not set-up in Cloudflare, take a look at their setup guide:
https://developers.cloudflare.com/fundamentals/setup/
Cloudflare Zero-Trust Tunnel setup
Login to Cloudflare and select Zero Trust > Access > Tunnels > Create a tunnel:
Complete the tunnel creation process:
Note down the tunnel connector authentication token:
In this case the token portion will be the string under cloudflared.exe service install in step 4 of "Install and run connector":
eyJhIjoiMTc2OGNiZWE5MGI1M2IwODI1YzIzNDMwMjQzYjZhZDgiLCJ0IjoiMDZhODA5ZGMtYzgyOC00NDU1LThhMzktMDgxYzAxNDZkOTM2IiwicyI6Ik5tWmlOVFl3TURNdE9EWTRNeTAwWW1GaExUazBaV0l0TURJNE5tSmpPRGhrTTJZMSJ9
Note: Your token will be different. Take note of your token for the next step.
Leave the browser open and ready to come back and complete in the final step.
Add a docker compose project for the Cloudflared tunnel
mkdir -p /opt/cloudflared-tunnel
cd /opt/cloudflared-tunnel
nano docker-compose.yml
version: "3.3"
services:
cloudflared-tunnel:
container_name: cloudflared-tunnel
image: cloudflare/cloudflared
restart: unless-stopped
command: tunnel run
environment:
- TUNNEL_TOKEN=<token>
networks:
- cf-tunnel
networks:
cf-tunnel:
name: cf-tunnel
Bring up your compose project with the new container:
docker compose up -d
Verify tunnel is showing an up status in the Cloudflare setup webpage.
Add "cf-tunnel" network to container sections docker-compose.yml files for containers will be exposed using Cloudflare Tunnel
...
networks:
- cf-tunnel
...
networks:
cf-tunnel:
external: true
Add routes for traffic to Cloudflare Tunnel for each container added to the cf-tunnel network by container name
Return to the browser with the Cloudflare tunnel setup in progress.
Select your domain or subdomain that will point to your hosted app.
Set type to HTTP or HTTPS depending on how container is exposed
Set URL to container-name:port. In my case, this will be ghost-app:2368.
Under Additional application settings > Set no verify SSL for containers using https with an invalid or self-signed certificate.
Save tunnel.
If you get any errors stating that DNS records exist, just go ahead and remove the DNS records if they do exist, as the tunnel setup tool will automatically add these back with the tunnel CNAME
Your tunnel should be active and ready for use.