3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cloudflare Tunnelで手元のサービスを公開

Last updated at Posted at 2025-03-21

Cloudflare Tunnelって何?

TunnelはパブリックIPやポート解放を必要とせず、外部からサービスにアクセスできる便利なサービスです。
これはCloudflare ZeroTrustのサービスで、無料で利用できます。

PagesとTunnelの比較

料金 リクエスト制限 サーバーレス 柔軟性 難しさ
Pages Free ~ 100,000 /day ⚪︎
Tunnel Free 無制限 × ⚪︎
  • Pages
    Pagesはサーバーレス重視な代わり柔軟性が低い印象。
    大量のリクエストを捌くAPIとかは従量課金のためおすすめできない。
  • Tunnel
    Tunnelはサーバーが必要だが、柔軟性が高い印象。
    完全無料のため、サーバーさえ確保できていればこちらの方がおすすめ。
    ただし、インフラ等のプログラミング以外の知識もある程度必要。

手元でTunnelを起動

以下のスクリプトを任意の場所に設置し、chmod +xで実行権限をつけます
実行方法は./cftunnel.sh <tunnel name> <domain> <url>です
例:./cftunnel.sh test test.example.com http://localhost:3000

注意書き:

#!/bin/bash

GREEN='\033[0;32m'
RESET='\033[0m'
PS4="[  ${GREEN}OK${RESET}  ] "
set -x

if [ ! -e "$HOME/.cloudflared/cert.pem" ]; then
    cloudflared tunnel login
fi

if [ -n "$1" -a -n "$2" -a -n "$3" ]; then
	cloudflared tunnel delete "$1" 2> /dev/null
    cloudflared tunnel create "$1" 2>&1 \
		| sed -nE 's/.*([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}).*/\1/p;q' \
		| xargs -I{} mv $HOME/.cloudflared/{}.json "$HOME/.cloudflared/${1}.json"
	cloudflared tunnel route dns -f "$1" "$2"
	cat <<-EOF | tee $HOME/.cloudflared/${1}-config.yaml
		tunnel: ${1}
		credentials-file: .cloudflared/${1}.json
		no-autoupdate: true
		ingress:
		- hostname: ${2}
		  service: ${3}
		- service: http_status:404
	EOF
fi;

if [ -e "$HOME/.cloudflared/${1}-config.yaml" ]; then
	cloudflared tunnel --config $HOME/.cloudflared/${1}-config.yaml run
fi
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?