Sandbox SDK Sandbox SDK Sandbox SDK · Lab 1/7 Lab 1/7 Lab 1/7 · 20 phút · 20 min · 20 នាទី

01

Bắt đầu với Sandbox SDK Getting Started with Sandbox SDK ចាប់ផ្តើមជាមួយ Sandbox SDK

Dựng Sandbox Cloudflare đầu tiên và chạy lệnh trong container cô lập trên edge. Set up your first Cloudflare Sandbox and execute commands in an isolated container environment. Learn the fundamentals of secure code execution at the edge. រៀបចំ Sandbox Cloudflare ដំបូង និងរត់ពាក្យបញ្ជាក្នុង container បំបែកនៅ edge។

Nội dung bước (lệnh, code) giữ nguyên tiếng Anh từ nguồn chính thức. Step body (commands, code) stays in English from the official source. ខ្លឹមសារជំហាន (ពាក្យបញ្ជា និង code) រក្សាភាសាអង់គ្លេសពីប្រភពផ្លូវការ។ labs.cloudflare.dev ↗

Cần trước Prerequisites តម្រូវការជាមុន

  • Docker đã cài và đang chạy Docker installed and running Docker បានដំឡើង និងកំពុងរត់
  • Node.js v20+ Node.js v20+ Node.js v20+
  • Tài khoản Cloudflare Cloudflare Account គណនី Cloudflare
  • Terminal / dòng lệnh Terminal/Command Line Terminal / ពាក្យបញ្ជា

Bạn sẽ làm được Learning objectives គោលបំណងសិក្សា

  • Tạo project Sandbox SDK từ template chính thức Create a Sandbox SDK project from the official template បង្កើត project Sandbox SDK ពី template ផ្លូវការ
  • Hiểu cấu trúc và kiến trúc project Understand the project structure and architecture យល់រចនាសម្ព័ន្ធ និងស្ថាបត្យកម្ម project
  • Chạy sandbox đầu tiên trên local với Docker Run your first sandbox locally with Docker រត់ sandbox ដំបូងលើ local ជាមួយ Docker
  • Chạy lệnh trong môi trường cô lập Execute commands in an isolated environment រត់ពាក្យបញ្ជាក្នុងបរិស្ថានបំបែក

Bước 1: Tạo project sandbox đầu tiên Step 1: Create Your First Sandbox Project ជំហាន 1: បង្កើត project sandbox ដំបូង

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
A Cloudflare Workers project with Sandbox SDK integration, ready to run isolated code.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Sandboxes enable safe execution of untrusted code, including AI-generated code in containers isolated from everything else.

Run the following command to scaffold a new project from the official minimal template:

Run the following command to scaffold a new project from the official minimal template:

Run the following command to scaffold a new project from the official minimal template:

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

When prompted, choose the following options:

When prompted, choose the following options:

When prompted, choose the following options:

txt
├ Do you want to use git for version control?
│ yes
├ Do you want to add an AGENTS.md file to help AI coding tools understand Cloudflare APIs?
│ yes
├ Do you want to deploy your application?
│ no

Once scaffolding is complete, you will see the following output in your terminal:

Once scaffolding is complete, you will see the following output in your terminal:

Once scaffolding is complete, you will see the following output in your terminal:

txt
🎉  SUCCESS  Application created successfully!

💻 Continue Developing
Change directories: cd my-sandbox
Deploy: npm run deploy

📖 Explore Documentation
https://developers.cloudflare.com/workers

🐛 Report an Issue
https://github.com/cloudflare/workers-sdk/issues/new/choose

💬 Join our Community
https://discord.cloudflare.com
────────────────────────────────────────────────────────────

Next, navigate into your new project and install dependencies:

Next, navigate into your new project and install dependencies:

Next, navigate into your new project and install dependencies:

bash
cd my-sandbox
npm install

Bước 2: Xem cấu trúc project Step 2: Explore the Project Structure ជំហាន 2: មើលរចនាសម្ព័ន្ធ project

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
A clear understanding of each file's purpose and how the pieces fit together.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Knowing the structure lets you confidently customize and extend your sandbox applications.
txt
my-sandbox/
├── src/
│   └── index.ts          # Worker with sandbox integration
├── wrangler.jsonc        # Cloudflare Workers + Container config
├── Dockerfile            # Container definition
└── package.json          # Dependencies

Open wrangler.jsonc and notice the key configuration:

Open wrangler.jsonc and notice the key configuration:

Open wrangler.jsonc and notice the key configuration:

json
{
  "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"
    }
  ]
}

The containers block tells Cloudflare to build your Dockerfile and make it available to the Sandbox Durable Object. The Durable Object manages lifecycle and state for each sandbox instance.

The containers block tells Cloudflare to build your Dockerfile and make it available to the Sandbox Durable Object. The Durable Object manages lifecycle and state for each sandbox instance.

The containers block tells Cloudflare to build your Dockerfile and make it available to the Sandbox Durable Object. The Durable Object manages lifecycle and state for each sandbox instance.

Now open src/index.ts:

Now open src/index.ts:

Now open src/index.ts:

typescript
import { getSandbox } from "@cloudflare/sandbox";

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

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

    // Get or create a sandbox instance
    const sandbox = getSandbox(env.Sandbox, "my-sandbox");

    if (url.pathname === "/run") {
      const result = await sandbox.exec('echo "2 + 2 = $((2 + 2))"');
      return Response.json({
        output: result.stdout,
        error: result.stderr,
        exitCode: result.exitCode,
        success: result.success,
      });
    }

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

Key concepts:

Key concepts:

Key concepts:

  • getSandbox(binding, id) — Gets or creates a sandbox instance. The id lets you maintain multiple isolated environments
  • Sandbox is lazy-initialized on first use — no upfront cost until you actually need it
  • exec() runs a shell command and returns structured output

Bước 3: Chạy sandbox trên local Step 3: Run Your Sandbox Locally ជំហាន 3: រត់ sandbox លើ local

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
A running local development environment with Docker powering your isolated container.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Local development lets you iterate quickly and test sandbox code before deploying to production.
bash
npm run dev
txt
⛅️ wrangler 4.x.x
───────────────────
Your Worker has access to the following bindings:
env.Sandbox (Sandbox) — Durable Object…[wrangler:inf] Ready on http://localhost:8787

Bước 4: Chạy lệnh đầu tiên Step 4: Execute Your First Command ជំហាន 4: រត់ពាក្យបញ្ជាដំបូង

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
A successful command execution inside your isolated sandbox, with structured output back to your Worker.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
This validates your entire setup and demonstrates the core sandbox capability end-to-end.

In a new terminal, run:

In a new terminal, run:

In a new terminal, run:

bash
curl http://localhost:8787/run
json
{
  "output": "2 + 2 = 4\n",
  "error": "",
  "exitCode": 0,
  "success": true
}
  • Docker not running: Open Docker Desktop and wait for it to fully start before running npm run dev
  • npm not found: Install Node.js v18+ from nodejs.org
  • Port 8787 busy: Use npm run dev -- --port 8788 and update your curl commands
  • Container build fails: Ensure Docker has enough available memory and disk space in its settings
  • Template not found: Update npm with npm install -g npm@latest and try again

✅ Your sandbox is live! You’ve created an isolated execution environment and run your first command inside it. Next, you’ll master the core APIs for commands and file operations.

✅ Your sandbox is live! You’ve created an isolated execution environment and run your first command inside it. Next, you’ll master the core APIs for commands and file operations.

✅ Your sandbox is live! You’ve created an isolated execution environment and run your first command inside it. Next, you’ll master the core APIs for commands and file operations.