Skip to content

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

Sandbox オプション

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

getSandbox() でサンドボックスインスタンスを作成するときにオプションを渡し、サンドボックスの動作を設定します。

利用できるオプション

import { getSandbox } from '@cloudflare/sandbox';

const sandbox = getSandbox(binding, sandboxId, options?: SandboxOptions);

enableDefaultSession

: boolean デフォルト: true

明示的な sessionId なしでサンドボックスメソッドを呼んだときの動作を制御します。true のとき、暗黙の操作はサンドボックスのデフォルトセッションを使い、呼び出し間のシェル状態を保持します。false のとき、暗黙の操作は分離して実行され、明示的にセッションを指定しない限り、前の呼び出しのシェル状態は引き継ぎません。

対話的またはステートフルなワークフローで、コマンドが作業ディレクトリとエクスポートした変数を共有すべき場合は enableDefaultSession: true を使います。ステートレスなリクエスト処理で、1 回の呼び出しが次に影響してはいけない場合は enableDefaultSession: false を使います。false にすることを推奨します。デフォルトセッションのサポートは将来の Sandbox SDK バージョンで削除され、今後は createSession() を明示的に使うのが望ましいパターンです。

// Default behavior: implicit operations use the default session
const statefulSandbox = getSandbox(env.Sandbox, "user-123");

await statefulSandbox.exec("cd /workspace/app");
const statefulResult = await statefulSandbox.exec("pwd");
// statefulResult.stdout: "/workspace/app"
// The second exec inherited the working directory from the first.

// Sessionless behavior: implicit operations do not share shell state
const statelessSandbox = getSandbox(env.Sandbox, "api-worker", {
	enableDefaultSession: false,
});

await statelessSandbox.exec("cd /workspace/app");
const statelessResult = await statelessSandbox.exec("pwd");
// statelessResult.stdout: "/workspace"
// The second exec did not inherit shell state from the first.
// Default behavior: implicit operations use the default session
const statefulSandbox = getSandbox(env.Sandbox, 'user-123');

await statefulSandbox.exec('cd /workspace/app');
const statefulResult = await statefulSandbox.exec('pwd');
// statefulResult.stdout: "/workspace/app"
// The second exec inherited the working directory from the first.

// Sessionless behavior: implicit operations do not share shell state
const statelessSandbox = getSandbox(env.Sandbox, 'api-worker', {
  enableDefaultSession: false
});

await statelessSandbox.exec('cd /workspace/app');
const statelessResult = await statelessSandbox.exec('pwd');
// statelessResult.stdout: "/workspace"
// The second exec did not inherit shell state from the first.

keepAlive

: boolean デフォルト: false

自動シャットダウンを防ぎ、コンテナを無期限に生存させます。true のとき、コンテナは退避を防ぐため 30 秒ごとにハートビート ping を自動送信し、自動タイムアウトしません。

仕組み: サンドボックスは 30 秒ごとに、コンテナへ軽量な ping リクエストを自動でスケジュールします。リソース負荷を抑えつつ、非アクティブによる退避を防ぎます。setKeepAlive() で keepAlive を動的に有効または無効にもできます。

keepAlive フラグは Durable Object のハイバネーションと起床をまたいで保持されます。一度有効にすれば、サンドボックスがハイバネーションから復帰したあとに再設定する必要はありません。

// For long-running processes that need the container to stay alive
const sandbox = getSandbox(env.Sandbox, "user-123", {
	keepAlive: true,
});

// Run your long-running process
await sandbox.startProcess("python long_running_script.py");

// Important: Must explicitly destroy when done
try {
	// Your work here
} finally {
	await sandbox.destroy(); // Required to prevent containers running indefinitely
}
// For long-running processes that need the container to stay alive
const sandbox = getSandbox(env.Sandbox, 'user-123', {
  keepAlive: true
});

// Run your long-running process
await sandbox.startProcess('python long_running_script.py');

// Important: Must explicitly destroy when done
try {
  // Your work here
} finally {
  await sandbox.destroy(); // Required to prevent containers running indefinitely
}

sleepAfter

: string | number デフォルト: "10m"(10 分)

サンドボックスが自動スリープするまでの非アクティブ期間です。期間文字列("30s""5m""1h")または数値(秒)を受け取ります。

// Sleep after 30 seconds of inactivity
const sandbox = getSandbox(env.Sandbox, "user-123", {
	sleepAfter: "30s",
});

// Sleep after 5 minutes (using number)
const sandbox2 = getSandbox(env.Sandbox, "user-456", {
	sleepAfter: 300, // 300 seconds = 5 minutes
});
// Sleep after 30 seconds of inactivity
const sandbox = getSandbox(env.Sandbox, 'user-123', {
  sleepAfter: '30s'
});

// Sleep after 5 minutes (using number)
const sandbox2 = getSandbox(env.Sandbox, 'user-456', {
  sleepAfter: 300  // 300 seconds = 5 minutes
});

containerTimeouts

: object

コンテナ起動操作のタイムアウトを設定します。

// Extended startup with custom Dockerfile work
// (installing packages, starting services before SDK)
const sandbox = getSandbox(env.Sandbox, "data-processor", {
	containerTimeouts: {
		portReadyTimeoutMS: 180_000, // 3 minutes for startup work
	},
});

// Wait longer during traffic spikes
const sandbox2 = getSandbox(env.Sandbox, "user-env", {
	containerTimeouts: {
		instanceGetTimeoutMS: 60_000, // 1 minute for provisioning
	},
});
// Extended startup with custom Dockerfile work
// (installing packages, starting services before SDK)
const sandbox = getSandbox(env.Sandbox, 'data-processor', {
  containerTimeouts: {
    portReadyTimeoutMS: 180_000  // 3 minutes for startup work
  }
});

// Wait longer during traffic spikes
const sandbox2 = getSandbox(env.Sandbox, 'user-env', {
  containerTimeouts: {
    instanceGetTimeoutMS: 60_000   // 1 minute for provisioning
  }
});

利用できるタイムアウトオプション:

  • instanceGetTimeoutMS - Cloudflare が新しいコンテナインスタンスをプロビジョニングするまでの待ち時間です。多数のコンテナが同時にプロビジョニングされるトラフィックスパイク時は増やします。デフォルト: 30000(30 秒)
  • portReadyTimeoutMS - サンドボックス API が利用可能になるまでの待ち時間です。ベース Dockerfile にカスタムの起動処理(パッケージのインストール、サービスの起動)を追加している場合は増やします。デフォルト: 90000(90 秒)

環境変数による上書き:

  • SANDBOX_INSTANCE_TIMEOUT_MS - instanceGetTimeoutMS を上書きします
  • SANDBOX_PORT_TIMEOUT_MS - portReadyTimeoutMS を上書きします

優先順位: options > env vars > SDK のデフォルト

ログ

: 環境変数

デバッグと監視向けに SDK のログを制御します。Worker の wrangler.jsonc で設定します。

利用できるオプション:

  • SANDBOX_LOG_LEVEL - 最小ログレベル: debuginfowarnerrorデフォルト: info
  • SANDBOX_LOG_FORMAT - 出力形式: jsonprettyデフォルト: json
{
	"vars": {
		"SANDBOX_LOG_LEVEL": "debug",
		"SANDBOX_LOG_FORMAT": "pretty"
	}
}
[vars]
SANDBOX_LOG_LEVEL = "debug"
SANDBOX_LOG_FORMAT = "pretty"

ローカル開発では debug + pretty を使います。本番(構造化ログ)では info または warn + json を使います。

normalizeId

: boolean デフォルト: false(将来のバージョンで true になります)

サンドボックス作成時に ID を小文字にします。true のとき、指定した ID は Durable Object 作成前に小文字化されます(例: "MyProject-123" → "myproject-123")。

なぜ重要か: プレビュー URL はホスト名からサンドボックス ID を取り出します。DNS は大文字小文字を区別しないため、ホスト名は常に小文字です。正規化しないと、"MyProject-123" で作成したサンドボックスは、URL ルーティングが "myproject-123"(別の Durable Object)を探すため、プレビュー URL から到達できなくなります。

// Without normalization (default)
const sandbox1 = getSandbox(env.Sandbox, "MyProject-123");
// Creates Durable Object with ID: "MyProject-123"
// Preview URL: 8000-myproject-123.example.com
// Problem: URL routes to "myproject-123" (different DO)

// With normalization
const sandbox2 = getSandbox(env.Sandbox, "MyProject-123", {
	normalizeId: true,
});
// Creates Durable Object with ID: "myproject-123"
// Preview URL: 8000-myproject-123.example.com
// Works: URL routes to "myproject-123" (same DO)
// Without normalization (default)
const sandbox1 = getSandbox(env.Sandbox, 'MyProject-123');
// Creates Durable Object with ID: "MyProject-123"
// Preview URL: 8000-myproject-123.example.com
// Problem: URL routes to "myproject-123" (different DO)

// With normalization
const sandbox2 = getSandbox(env.Sandbox, 'MyProject-123', {
  normalizeId: true
});
// Creates Durable Object with ID: "myproject-123"
// Preview URL: 8000-myproject-123.example.com
// Works: URL routes to "myproject-123" (same DO)

normalizeId を使うタイミング

次の場合は normalizeId: true を使います。

  • プレビュー URL を使う - ID に大文字が含まれる場合、ポート公開に必要です
  • 新規プロジェクト - このオプションを有効にするか、最初から小文字の ID を使います(どちらでも動作します)
  • 既存コードの移行 - このオプションを有効にして新しいサンドボックスを作成します。古い大文字 ID のサンドボックスは、いずれ破棄されます(明示的な破棄、またはタイムアウト後)

ベストプラクティス: 最初から小文字の ID を使います('MyProject-123' ではなく 'my-project-123')。

sleepAfter を使うタイミング

カスタムの sleepAfter 値は次の目的で使います。

  • コスト削減 - 頻度の低いワークロードには短いタイムアウト(例: "1m"
  • 可用性の延長 - 対話的なワークフローには長いタイムアウト(例: "30m"
  • パフォーマンスの調整 - アプリケーションの利用パターンに合わせて微調整

デフォルトの 10 分タイムアウトは、ほとんどのアプリケーションで十分です。必要に応じて調整してください。

keepAlive を使うタイミング

次の場合は keepAlive: true を使います。

  • 長時間のビルド - ステップ間にアイドル期間がある CI/CD パイプライン
  • バッチ処理 - バッチ間に間隔があるウェーブ状のデータ処理
  • 監視タスク - 外部サービスを定期的に確認するプロセス
  • 対話セッション - コンテナを利用可能な状態に保つユーザー主導のワークフロー

keepAlive では、コンテナは退避を防ぐため 30 秒ごとにハートビート ping を自動送信し、自動スリープしません。ライフサイクルを明示的に制御するシナリオで使います。

関連情報

役に立ちましたか?