Skip to content

非公式 / UnofficialCloudflare, Inc. 非提携。アカウント情報は入力しないでください。Not affiliated with Cloudflare, Inc. Do not enter Cloudflare credentials here.Official docsこのサイトについてプライバシー

プライベート API またはウェブサイトにアクセスする

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

この例では、公開インターネットに露出していないプライベート REST API へのアクセス方法を示します。このガイドでは、内部 API 向けの VPC Service を設定し、その API にリクエストする Worker を作成し、変更を検証するために Worker をデプロイします。

前提条件

  • VPC / 仮想ネットワーク上で稼働している仮想マシン / EC2 インスタンス
  • VPC / 仮想ネットワーク上で稼働しているプライベート API またはウェブサイト。cloudflared を実行する仮想マシンからのアクセスを許可するセキュリティルールがあること
  • Workers VPC にアクセスできる Workers アカウント

1. Cloudflare Tunnel を設定する

Cloudflare Tunnel は、プライベートネットワークから Cloudflare への安全な接続を作ります。このトンネルにより、Workers がプライベートリソースへ安全にアクセスできます。

  1. Workers VPC ダッシュボード ↗ を開き、Tunnels タブを選択します。

  2. 作成 を選択して、新しいトンネルを作ります。

  3. トンネル名(例: private-api-tunnel)を入力し、トンネルを保存 を選択します。

  4. OS とアーキテクチャを選びます。ダッシュボードに、環境向けのインストール手順が表示されます。

  5. 表示されたコマンドに従い、VM に cloudflared をダウンロードしてインストールし、固有のトークン付きでサービスインストールコマンドを実行します。

トンネルが接続されると、ダッシュボードに確認が表示されます。次の手順のためにトンネル ID を控えます。

2. Workers VPC Service を作成する

まず、内部 API 向けの Workers VPC Service を作成します。

npx wrangler vpc service create api-service \
  --type http \
  --tunnel-id <YOUR_TUNNEL_ID> \
  --ipv4 10.0.1.50 \
  --http-port 8080

ホスト名を使って、サービス向けの VPC Service を作成することもできます。

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

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

3. Worker を設定する

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

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "private-api-gateway",
	"main": "src/index.js",
	// Set this to today's date
	"compatibility_date": "2026-11-14",
	"vpc_services": [
		{
			"binding": "INTERNAL_API",
			"service_id": "<YOUR_SERVICE_ID>",
			"remote": true
		}
	]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "private-api-gateway"
main = "src/index.js"
# Set this to today's date
compatibility_date = "2026-11-14"

[[vpc_services]]
binding = "INTERNAL_API"
service_id = "<YOUR_SERVICE_ID>"
remote = true

4. Worker を実装する

Workers のコードでは、VPC Service バインディングを使ってサービスへリクエストを送ります。

index.jsjs
export default {
	async fetch(request, env, ctx) {
		try {
			// Fetch data from internal API and process it before returning
			const response = await env.INTERNAL_API.fetch("http://10.0.1.50:8080/api/data");

			// Use the response of the private API to perform more logic in Workers, before returning the final response
			return response;
		} catch (error) {
			return new Response("Service unavailable", { status: 503 });
		}
	},
};

このガイドでは、Workers で簡単なプロキシを作る方法を示しています。一方で、VPC Services を使って API を直接取得し、レスポンスを加工すれば、Workers 上でより本格的なフルスタックやバックエンドの機能も構築できます。

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

作成した Worker をデプロイしてテストできます。

npx wrangler deploy
# Test GET request
curl https://private-api-gateway.workers.dev

次のステップ

役に立ちましたか?