すでに Sandbox を使っている Workers プロジェクト、または Sandbox テンプレートから作った新規プロジェクトで次を実行します。
npm i @cloudflare/sandbox@nextyarn add @cloudflare/sandbox@nextpnpm add @cloudflare/sandbox@nextbun add @cloudflare/sandbox@nextWorker と サンドボックスのコンテナイメージを、同じプレビュー系列からビルドしてデプロイします。
import { Sandbox } from "@cloudflare/sandbox";
export { Sandbox };import { Sandbox } from "@cloudflare/sandbox";
export { Sandbox };wrangler の Durable Object バインディングとコンテナ設定はそのまま使います。プレビュー専用のトランスポート変数は不要です。
exec() は argv(実行ファイルのパスまたは名前と、その引数の配列)からプログラムを起動します。サンドボックスがプロセスを起動できるまで待ち、プロセスハンドルを返します。プロセスの終了は待ちません。
結果は output() などのハンドルメソッドで集めます。ストリームする場合は logs() を使います。
import { getSandbox, proxyToSandbox } from "@cloudflare/sandbox";
export { Sandbox } from "@cloudflare/sandbox";
export default {
async fetch(request, env) {
const proxy = await proxyToSandbox(request, env);
if (proxy) return proxy;
const sandbox = getSandbox(env.Sandbox, "preview-demo");
const process = await sandbox.exec(["python3", "-c", "print(2 + 2)"]);
const output = await process.output({ encoding: "utf8" });
return Response.json({
id: process.id,
pid: process.pid,
stdout: output.stdout,
exitCode: output.exitCode,
});
},
};import { getSandbox, proxyToSandbox } from "@cloudflare/sandbox";
export { Sandbox } from "@cloudflare/sandbox";
type Env = {
Sandbox: DurableObjectNamespace<import("@cloudflare/sandbox").Sandbox>;
};
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const proxy = await proxyToSandbox(request, env);
if (proxy) return proxy;
const sandbox = getSandbox(env.Sandbox, "preview-demo");
const process = await sandbox.exec(["python3", "-c", "print(2 + 2)"]);
const output = await process.output({ encoding: "utf8" });
return Response.json({
id: process.id,
pid: process.pid,
stdout: output.stdout,
exitCode: output.exitCode,
});
},
};argv の各要素は、プロセスへの 1 つの引数です。SDK はシェルを実行せず、argv をシェルエスケープしません。要素内のスペースや特殊文字は、その引数の中に残ります。
シェル構文(&&、パイプ、リダイレクト、グロブ)を使う場合は、明示的にシェルを起動し、スクリプトを独立した引数として渡します。
const process = await sandbox.exec([
"/bin/bash",
"-lc",
"echo hello && uname -a",
]);
const { stdout } = await process.output({ encoding: "utf8" });const process = await sandbox.exec([
"/bin/bash",
"-lc",
"echo hello && uname -a",
]);
const { stdout } = await process.output({ encoding: "utf8" });await sandbox.exec(...)はプロセスを作成します。終了は待ちません。完了を待つにはoutput()、waitForExit()、または他のハンドルメソッドを使います。- 各
exec()は独立しています。ある呼び出しでのcdやexportは、次の呼び出しには引き継がれません。 - 必要な場合は、毎回の
exec()にcwdとenvを渡します。サンドボックス全体の値にはsetEnvVarsを使います。環境変数 を参照してください。 - プロセスは、そのサンドボックスの現在のコンテナでのみ動きます。コンテナが停止または置き換わったら、新しいプロセスを起動します。モデルは Sandbox のライフサイクル を参照してください。
- 本番トラフィックの前に、再試行してよい失敗を確認します。エラーと回復 を参照してください。
- Sandbox のライフサイクル — サンドボックス ID、コンテナ、停止、置き換え
- プロセス実行 —
exec()、ハンドル、リクエストをまたいだ継続作業 - エラーと回復 — 再試行、中断された呼び出し、古いハンドル
- 移行 — 既存の安定版アプリを更新する
- API リファレンス — プロセス、ターミナル、エラー
- ターミナル — 対話型 PTY とブラウザー接続
- 拡張