Self-hosting on Termux via Cloudflare Tunnel

A suitable solution for those who have an unused Android device and no white IP.

1. Assets

Example

DOMAIN=domain.com
TUNNEL=main
URL=http://localhost:1024
CONFIG=~/.cloudflared/config-${TUNNEL}.yml

2. Create a tunnel

pkg install cloudflared
cloudflared tunnel login
cloudflared tunnel create ${TUNNEL}
ID=$(cloudflared tunnel list | awk -v NAME=${TUNNEL} '$2 == NAME { print $1 }')

3. Create a config

cat << EOF > ${CONFIG}
url: ${URL}
tunnel: ${ID}
credentials-file: /data/data/com.termux/files/home/.cloudflared/${ID}.json
EOF

4. Start routing traffic

cloudflared tunnel route dns ${TUNNEL} ${DOMAIN}

5. Run the tunnel

cloudflared tunnel --config ${CONFIG} run ${TUNNEL}

6. Runit service (optional)

pkg install termux-services
LOG=${PREFIX}/var/service/cloudflared/log
mkdir -p ${LOG}
ln -sf ${PREFIX}/share/termux-services/svlogger ${LOG}/run
RUN=${PREFIX}/var/service/cloudflared/run
cat << EOF > ${RUN}
#!/bin/sh
exec cloudflared tunnel --config ${CONFIG} run ${TUNNEL}
EOF
chmod +x ${RUN}
sv-enable cloudflared
sv up cloudflared

Resources