Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Workers からプライベートサービスへルーティングする

最終更新 Markdown で表示Agent セットアップ

この例では、Workers VPC を使って、URL パスに基づいてリクエストを振り分け、認証とレート制限を提供し、内部サービス間で負荷分散する中央ゲートウェイを作成します。

前提条件

  • VPC / 仮想ネットワーク上で稼働する複数のプライベート API またはサービス(ここではユーザーサービスと注文サービスを使います)
  • 設定済みで稼働中の Cloudflare Tunnel(セットアップは はじめに に従うか、ダッシュボードからトンネルを作成します)
  • Workers VPC にアクセスできる Workers アカウント

1. VPC Services を作成する

まず、ホスト名を使って内部 API 用のサービスを作成します。

# Create user service
npx wrangler vpc service create user-service \
  --type http \
  --tunnel-id <YOUR_TUNNEL_ID> \
  --hostname user-api.internal.example.com

# Create orders service
npx wrangler vpc service create order-service \
  --type http \
  --tunnel-id <YOUR_TUNNEL_ID> \
  --hostname orders-api.internal.example.com

次の手順で使うため、返されたサービス ID を控えます。

2. Worker を設定する

Wrangler 設定ファイルを更新します。

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "api-gateway",
	"main": "src/index.js",
	// Set this to today's date
	"compatibility_date": "2026-09-20",
	"vpc_services": [
		{
			"binding": "USER_SERVICE",
			"service_id": "<YOUR_USER_SERVICE_ID>"
		},
		{
			"binding": "ORDER_SERVICE",
			"service_id": "<YOUR_ORDER_SERVICE_ID>"
		}
	]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "api-gateway"
main = "src/index.js"
# Set this to today's date
compatibility_date = "2026-09-20"

[[vpc_services]]
binding = "USER_SERVICE"
service_id = "<YOUR_USER_SERVICE_ID>"

[[vpc_services]]
binding = "ORDER_SERVICE"
service_id = "<YOUR_ORDER_SERVICE_ID>"

3. Worker を実装する

Workers のコードで、VPC Service バインディングを使い、適切なサービスへリクエストをルーティングします。

index.jsjs
export default {
	async fetch(request, env, ctx) {
		const url = new URL(request.url);

		// Route to internal services
		if (url.pathname.startsWith('/api/users')) {
			const response = await env.USER_SERVICE.fetch("https://user-api.internal.example.com" + url.pathname);
			return response;
		} else if (url.pathname.startsWith('/api/orders')) {
			const response = await env.ORDER_SERVICE.fetch("https://orders-api.internal.example.com" + url.pathname);
			return response;
		}

		return new Response('Not Found', { status: 404 });
	},
};

4. デプロイしてテストする

これで Worker をデプロイし、テストできます。

npx wrangler deploy
# Test user service requests
curl https://api-gateway.workers.dev/api/users

# Test orders service requests
curl https://api-gateway.workers.dev/api/orders

次のステップ

役に立ちましたか?