Skip to content

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

はじめに

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

安全なコード実行環境である Sandbox SDK で、最初のアプリケーションを作ります。このガイドでは、分離されたコンテナで Python コードを実行し、ファイルを操作できる Worker を作成します。

前提条件

  1. Cloudflare アカウント ↗ に登録します。
  2. Node.js ↗ をインストールします。

Node.js のバージョンマネージャー

権限の問題を避け、Node.js のバージョンを切り替えられるよう、Volta ↗ や nvm ↗ などの Node バージョンマネージャーを使います。このガイドの後半で説明する Wrangler には、Node バージョン 16.17.0 以降が必要です。

ローカルで Docker が動いていることを確認する

Sandbox SDK は、Worker と一緒にコンテナイメージをビルドするため Docker ↗ を使います。

wrangler deploy を実行するときは、ローカルで Docker が動いている必要があります。多くの場合、Docker のインストールには Docker Desktop のインストール手順 ↗ に従うのが最も簡単です。Colima ↗ など、ほかのツールでも動作する場合があります。

ターミナルで docker info を実行すると、Docker が正しく動いているかを確認できます。Docker が動いていれば、コマンドは成功します。Docker が動いていない場合、docker info はハングするか、「Cannot connect to the Docker daemon」を含むエラーを返します。

1. 新しいプロジェクトを作成する

新しい Sandbox SDK プロジェクトを作成します。

npm create cloudflare@latest -- my-sandbox --template=cloudflare/sandbox-sdk/examples/minimal

これで、必要なものがそろった my-sandbox ディレクトリができます。

  • src/index.ts - サンドボックス連携付きの Worker
  • wrangler.jsonc - Workers と Containers の設定
  • Dockerfile - コンテナ環境の定義
cd my-sandbox

2. テンプレートを確認する

テンプレートは、サンドボックスの中核機能を示す最小の Worker を提供します。

import { getSandbox, proxyToSandbox, type Sandbox } from "@cloudflare/sandbox";

export { Sandbox } from "@cloudflare/sandbox";

type Env = {
	Sandbox: DurableObjectNamespace<Sandbox>;
};

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const url = new URL(request.url);

		// Get or create a sandbox instance. For user-facing apps,
		// derive this ID from the authenticated user.
		const sandbox = getSandbox(env.Sandbox, "my-sandbox");

		// Execute Python code
		if (url.pathname === "/run") {
			const result = await sandbox.exec('python3 -c "print(2 + 2)"');
			return Response.json({
				output: result.stdout,
				error: result.stderr,
				exitCode: result.exitCode,
				success: result.success,
			});
		}

		// Work with files
		if (url.pathname === "/file") {
			await sandbox.writeFile("/workspace/hello.txt", "Hello, Sandbox!");
			const file = await sandbox.readFile("/workspace/hello.txt");
			return Response.json({
				content: file.content,
			});
		}

		return new Response("Try /run or /file");
	},
};

主な概念:

  • getSandbox() - ID でサンドボックスインスタンスを取得または作成します。同じサンドボックスに再接続するには、安定した ID を使います。ユーザー向けアプリでは、ID を 1 ユーザーにスコープします。
  • sandbox.exec() - サンドボックス内でシェルコマンドを実行し、stdout、stderr、終了コードを取得します。
  • sandbox.writeFile() / readFile() - サンドボックスのファイルシステムでファイルを書き込み・読み取ります。

3. ローカルでテストする

開発サーバーを起動します。

npm run dev
# If you expect to have multiple sandbox instances, you can increase `max_instances`.

エンドポイントをテストします。

# Execute Python code
curl http://localhost:8787/run

# File operations
curl http://localhost:8787/file

コマンド出力とファイル内容を含む JSON レスポンスが表示されます。

4. 本番にデプロイする

Worker とコンテナをデプロイします。

npx wrangler deploy

このコマンドは次を行います。

  1. Docker でコンテナイメージをビルドします
  2. Cloudflare の Container Registry にプッシュします
  3. Worker をグローバルにデプロイします

デプロイ状態を確認します。

npx wrangler containers list

5. デプロイをテストする

Worker の URL(デプロイ出力に表示されます)を開きます。

# Replace with your actual URL
curl https://my-sandbox.YOUR_SUBDOMAIN.workers.dev/run

サンドボックスはデプロイ済みで、分離されたコンテナでコードを実行できます。

設定の内容

wrangler.jsonc は、次の 3 つをつなぎます。

{
	"containers": [
		{
			"class_name": "Sandbox",
			"image": "./Dockerfile",
			"instance_type": "lite",
			"max_instances": 1,
		},
	],
	"durable_objects": {
		"bindings": [
			{
				"class_name": "Sandbox",
				"name": "Sandbox",
			},
		],
	},
	"migrations": [
		{
			"new_sqlite_classes": ["Sandbox"],
			"tag": "v1",
		},
	],
}
[[containers]]
class_name = "Sandbox"
image = "./Dockerfile"
instance_type = "lite"
max_instances = 1

[[durable_objects.bindings]]
class_name = "Sandbox"
name = "Sandbox"

[[migrations]]
new_sqlite_classes = [ "Sandbox" ]
tag = "v1"

環境変数、シークレット、カスタムイメージを含む詳細な設定オプションは Wrangler 設定リファレンス を参照してください。

次のステップ

動くサンドボックスができたら、ほかの機能も試してください。

役に立ちましたか?