创建首个沙箱
本快速开始会从 base 创建一个沙箱,写入文件,执行 shell 命令,打印结果,并删除沙箱。
你需要:
- 一个具备创建沙箱权限的 SeaCloud API Key。
- 目标环境中可访问
base官方模板。 - 本地已安装 Node.js、Python 或 Go。
- 运行环境可以访问
https://sandbox-gateway.cloud.seaart.ai。
1. 配置凭据
Section titled “1. 配置凭据”创建 SeaCloud API Key 后,在 shell 或运行时密钥管理中配置 Gateway 地址和 Token。
export SEACLOUD_BASE_URL="https://sandbox-gateway.cloud.seaart.ai"export SEACLOUD_API_KEY="YOUR_API_KEY"2. 安装 SDK
Section titled “2. 安装 SDK”npm install @seacloudai/sandboxpip install seacloud-sandboxgo get github.com/SeaCloudAI/sandbox-go3. 创建、执行并清理
Section titled “3. 创建、执行并清理”import { Sandbox } from "@seacloudai/sandbox";
const sandbox = await Sandbox.create("base", { waitReady: true, timeout: 1800,});
try { await sandbox.files.write("/root/workspace/hello.txt", "hello from node\n");
const run = await sandbox.commands.run("sh", { args: ["-lc", "pwd && cat /root/workspace/hello.txt"], });
console.log(run.exitCode, run.stdout);} finally { await sandbox.delete();}from sandbox import Sandbox
sandbox = Sandbox.create("base", waitReady=True, timeout=1800)
try: sandbox.files.write("/root/workspace/hello.txt", "hello from python\n")
run = sandbox.commands.run( "sh", args=["-lc", "pwd && cat /root/workspace/hello.txt"], )
print(run["exit_code"], run["stdout"])finally: sandbox.delete()ctx := context.Background()ready := truetimeout := int64(1800)
sbx, err := sandbox.Create(ctx, "base", &sandbox.CreateOptions{ WaitReady: &ready, Timeout: &timeout,})if err != nil { log.Fatal(err)}defer sbx.Delete(ctx)
files, _ := sbx.Files()_, _ = files.Write(ctx, "/root/workspace/hello.txt", []byte("hello from go\n"))
cmds, _ := sbx.Commands()run, _ := cmds.Run(ctx, "sh", &sandbox.CommandRunOptions{ Args: []string{"-lc", "pwd && cat /root/workspace/hello.txt"},})
log.Println(run.ExitCode, run.Stdout)命令应打印退出码 0,并输出类似内容:
/root/workspacehello from node不同语言的 stdout 包装可能不同,但成功运行应满足三个条件:
- 沙箱进入
running。 /root/workspace/hello.txt文件可读取。delete()清理时没有生命周期错误。
刚才你完成了什么
Section titled “刚才你完成了什么”| 步骤 | API 表面 |
|---|---|
| 创建沙箱 | SDK 内部调用 POST /api/v1/sandboxes |
| 等待就绪 | waitReady: true 等待运行时 API 可用 |
| 写入文件 | sandbox.files 背后的运行时文件系统 API |
| 执行命令 | sandbox.commands 背后的运行时进程 API |
| 删除沙箱 | sandbox.delete() 内部调用 DELETE /api/v1/sandboxes/:sandboxID |
首次运行排障
Section titled “首次运行排障”| 现象 | 检查项 |
|---|---|
401 或 403 | SEACLOUD_API_KEY 是否存在、有效,并属于目标项目。 |
template not found | 在目标环境列出官方模板,确认 base 可见。 |
| 沙箱等待过久 | 增加生命周期 timeout;查询沙箱详情中的 timeline 和 diagnostic。 |
| 缺少运行时凭据 | 查询沙箱详情,确认存在 envdUrl 和 envdAccessToken。 |
| 命令超时 | 增加运行时命令 timeoutMs;单位是毫秒,不是秒。 |
| 清理失败 | 使用 Sandbox ID 重试 delete(),再检查生命周期状态。 |
curl 冒烟测试
Section titled “curl 冒烟测试”SDK 设置失败时,可先用该命令验证 Gateway 和 API Key:
curl -sS "${SEACLOUD_BASE_URL}/api/v1/sandboxes" \ -H "X-API-Key: ${SEACLOUD_API_KEY}" \ -H "Content-Type: application/json" \ --data '{ "templateID": "base", "timeout": 1800, "waitReady": true }' | jq .保存返回的 sandboxID,测试后删除:
curl -sS -X DELETE "${SEACLOUD_BASE_URL}/api/v1/sandboxes/${SANDBOX_ID}" \ -H "X-API-Key: ${SEACLOUD_API_KEY}" -i