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

07

Deploy production Deploy to Production Deploy ទៅ production

Deploy sandbox lên mạng Cloudflare, cleanup bằng destroy(), quản lý lifecycle và checklist production. Deploy your sandbox application to Cloudflare's global network. Implement proper cleanup with destroy(), manage sandbox lifecycle, and apply the production checklist. Deploy sandbox ទៅបណ្តាញ Cloudflare cleanup ដោយ destroy() គ្រប់គ្រង lifecycle និង checklist production។

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 តម្រូវការជាមុន

  • Đã xong bước 6 Completed Step 6 បានបញ្ចប់ជំហាន 6
  • Mọi bước trước đang chạy local All previous steps working locally ជំហានមុនទាំងអស់កំពុងរត់ local
  • Tài khoản Cloudflare có quyền Workers Cloudflare account with Workers access គណនី Cloudflare មានសិទ្ធិ Workers

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

  • Deploy app sandbox bằng wrangler deploy Deploy a sandbox application with wrangler deploy Deploy កម្មវិធី sandbox ដោយ wrangler deploy
  • Cleanup sandbox bằng destroy() trong try/finally Implement sandbox cleanup using destroy() in try/finally Cleanup sandbox ដោយ destroy() ក្នុង try/finally
  • Dùng setKeepAlive() cho thao tác chạy lâu Use setKeepAlive() for long-running operations ប្រើ setKeepAlive() សម្រាប់ប្រតិបត្តិការរត់យូរ
  • Chạy checklist production trước khi live Apply the production checklist before going live រត់ checklist production មុន live
  • Monitor bản deploy trên dashboard Cloudflare Monitor your deployment from the Cloudflare dashboard Monitor ការដាក់ឱ្យប្រើលើ dashboard Cloudflare

Before deploying, verify each of these:

Before deploying, verify each of these:

Before deploying, verify each of these:

Security

Security

Security

  • Input validation on all user-provided data
  • Per-user sandbox isolation (never a shared sandbox)
  • Secrets stay in the Worker — not in sandbox env vars
  • Authentication gates access to code execution
  • Rate limiting configured (Workers rate limiting or a KV counter)

Performance & Reliability

Performance & Reliability

Performance & Reliability

  • Sandboxes are destroyed with destroy() when no longer needed
  • setKeepAlive(true) used for long-running operations, disabled when done
  • Error handling and timeouts on all exec() calls
  • Logging enabled in wrangler.jsonc

Bước 1: Deploy ứng dụng Step 1: Deploy Your Application ជំហាន 1: Deploy កម្មវិធី

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
Your sandbox application running on Cloudflare's global network.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Production deployment makes your app available worldwide via Cloudflare's edge, with automatic scaling and no infrastructure to manage.

Make sure you’re logged in to Wrangler:

Make sure you’re logged in to Wrangler:

Make sure you’re logged in to Wrangler:

bash
npx wrangler login

Then deploy:

Then deploy:

Then deploy:

bash
npm run deploy
txt
⛅️ wrangler 4.x.x Uploading worker script… Uploading container image…
(this takes 1-2 minutes on first deploy) ✨ Success! Published my-sandbox
(3.14s) https://my-sandbox.your-subdomain.workers.dev

Test the production URL:

Test the production URL:

Test the production URL:

bash
curl https://my-sandbox.your-subdomain.workers.dev/run

Bước 2: Cleanup sandbox Step 2: Implement Sandbox Cleanup ជំហាន 2: Cleanup sandbox

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
A pattern that guarantees sandbox resources are freed after every request.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Sandboxes consume CPU, memory, and disk space. Failing to destroy them causes resource leaks, higher costs, and eventually hitting capacity limits.

Use try/finally to ensure destroy() is always called, even when errors occur:

Use try/finally to ensure destroy() is always called, even when errors occur:

Use try/finally to ensure destroy() is always called, even when errors occur:

typescript
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const sessionId = crypto.randomUUID();
    const sandbox = getSandbox(env.Sandbox, sessionId);

    try {
      const result = await sandbox.exec("npm test");

      return Response.json({
        success: result.success,
        output: result.stdout,
      });
    } finally {
      // Always runs — even if exec() threw or the response already started
      await sandbox.destroy();
    }
  },
};

When to destroy vs. when to keep:

When to destroy vs. when to keep:

When to destroy vs. when to keep:

Bước 3: Quản lý lifecycle sandbox Step 3: Manage Sandbox Lifecycle ជំហាន 3: គ្រប់គ្រង lifecycle sandbox

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
Understanding and controlling every stage of the sandbox lifecycle.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Proper lifecycle management prevents timeouts on long tasks and resource leaks on abandoned sandboxes.

The full lifecycle:

The full lifecycle:

The full lifecycle:

txt
getSandbox()     →    use (exec, files, runCode, ...)    →    destroy()
    ↓                            ↓
Lazy init on              Reuse the same instance
first use                 across multiple calls

Lifecycle methods:

Lifecycle methods:

Lifecycle methods:

typescript
const sandbox = getSandbox(env.Sandbox, "my-sandbox");

// Prevent the sandbox from automatically sleeping (sends heartbeat pings)
await sandbox.setKeepAlive(true);

// Re-enable automatic sleep when you're done with long operations
await sandbox.setKeepAlive(false);

// Terminate the container and free all resources
await sandbox.destroy();
typescript
const sandbox = getSandbox(env.Sandbox, "my-sandbox", {
  sleepAfter: "30m", // sleep after 30 minutes of inactivity (default: "10m")
});

setKeepAlive for long-running tasks:

setKeepAlive for long-running tasks:

setKeepAlive for long-running tasks:

typescript
if (url.pathname === "/build" && request.method === "POST") {
  const sandbox = getSandbox(env.Sandbox, `build-${crypto.randomUUID()}`);

  try {
    // Prevent automatic sleep during the long build process
    await sandbox.setKeepAlive(true);

    // Clone, install, and build
    await sandbox.gitCheckout("https://github.com/my-org/my-app.git");
    await sandbox.exec("npm ci", {
      cwd: "/workspace/my-app",
      timeout: 120_000,
    });

    const buildResult = await sandbox.exec("npm run build", {
      cwd: "/workspace/my-app",
      timeout: 180_000,
    });

    return Response.json({
      success: buildResult.success,
      output: buildResult.stdout,
    });
  } finally {
    await sandbox.destroy();
  }
}

Bước 4: Cấu hình production Step 4: Production Configuration ជំហាន 4: កំណត់ production

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
An optimized wrangler.jsonc tuned for production workloads.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Development defaults (lite instances, low max_instances) are not suitable for real traffic. Choose an instance type that matches your workload.

Update your wrangler.jsonc for production:

Update your wrangler.jsonc for production:

Update your wrangler.jsonc for production:

jsonc
{
  "name": "my-sandbox",
  "main": "src/index.ts",
  "compatibility_date": "2026-01-06", // Update to your deploy date
  "compatibility_flags": ["nodejs_compat"],
  "observability": {
    "enabled": true,
  },
  "containers": [
    {
      "class_name": "Sandbox",
      "image": "./Dockerfile",
      "instance_type": "standard-1",
      "max_instances": 20,
    },
  ],
  "durable_objects": {
    "bindings": [
      {
        "class_name": "Sandbox",
        "name": "Sandbox",
      },
    ],
  },
  "migrations": [
    {
      "new_sqlite_classes": ["Sandbox"],
      "tag": "v1",
    },
  ],
}

Container instance types:

Container instance types:

Container instance types:

Scale max_instances based on your expected concurrent users. For most production apps, standard-1 is a good starting point.

Scale max_instances based on your expected concurrent users. For most production apps, standard-1 is a good starting point.

Scale max_instances based on your expected concurrent users. For most production apps, standard-1 is a good starting point.

Bước 5: Monitor bản deploy Step 5: Monitor Your Deployment ជំហាន 5: Monitor ការដាក់ឱ្យប្រើ

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
Visibility into your running production deployment via the Cloudflare dashboard and logs.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
You can't fix what you can't see — monitoring tells you when things go wrong before your users do.

In the Cloudflare Dashboard:

In the Cloudflare Dashboard:

In the Cloudflare Dashboard:

  1. Go to Workers & Pages → your worker
  2. Click Logs to see real-time invocation logs
  3. Check Metrics for request counts, error rates, and CPU time
  4. Open Settings → Observability to configure log retention

Test production is working:

Test production is working:

Test production is working:

bash
# Basic smoke test
curl https://my-sandbox.your-subdomain.workers.dev/run

# Code execution test
curl -X POST https://my-sandbox.your-subdomain.workers.dev/code \
  -H "Content-Type: application/json" \
  -d '{"code": "console.log(\"Production sandbox working!\", new Date().toISOString())"}'

Bạn đã xong lab Sandbox SDK! You completed the Sandbox SDK lab! អ្នកបានបញ្ចប់ lab Sandbox SDK!

You've gone from zero to a production-ready secure code execution environment on Cloudflare's global network.

You've gone from zero to a production-ready secure code execution environment on Cloudflare's global network.

You've gone from zero to a production-ready secure code execution environment on Cloudflare's global network.

What you built

What you built

What you built

  1. 01 Set up a sandbox project and executed your first command
  2. 02 Mastered exec(), writeFile(), readFile(), and listFiles()
  3. 03 Built a multi-language code executor with runCode()
  4. 04 Created an AI-powered code executor using Workers AI
  5. 05 Built a live app preview with git, processes, and port proxying
  6. 06 Applied production security: isolation, secrets, validation, auth
  7. 07 Deployed to Cloudflare's global network with proper lifecycle management

What to build next

What to build next

What to build next

Share what you built with #CloudflareSandbox and connect with the community!

Share what you built with #CloudflareSandbox and connect with the community!

Share what you built with #CloudflareSandbox and connect with the community!