lightning-sandboxes
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLightning AI Sandboxes
Lightning AI Sandboxes
A Sandbox is a fast-booting isolated VM for code execution. Ephemeral by default ( enables stop/resume via auto-snapshots). Import from the subpackage — (the top-level class is legacy; ignore it).
persistent=Truefrom lightning_sdk.sandbox import Sandboxlightning_sdk.sandbox.py_SandboxSandbox 是一种启动快速、用于代码执行的隔离 VM。默认是临时的( 可通过自动快照启用停止/恢复功能)。请从子包导入 —— (顶层的 中的 类是旧版实现,请忽略)。
persistent=Truefrom lightning_sdk.sandbox import Sandboxlightning_sdk.sandbox.py_SandboxSetup & auth (sandbox-specific)
安装与认证(沙箱专属)
bash
undefinedbash
undefinedUse the Lightning AI CLI from the current env; install or upgrade it there if it's missing or older than 2026.9.18
Use the Lightning AI CLI from the current env; install or upgrade it there if it's missing or older than 2026.9.18
v=$(lightning --version 2>/dev/null | sed -n 's/^Lightning CLI version //p')
[ -n "$v" ] && [ "$(printf '%s\n' 2026.9.18 "$v" | sort -V | head -1)" = 2026.9.18 ]
|| uv pip install -U lightning-sdk || python3 -m pip install -U lightning-sdk lightning --version # must print "Lightning CLI version …"; if not, see the table below
|| uv pip install -U lightning-sdk || python3 -m pip install -U lightning-sdk lightning --version # must print "Lightning CLI version …"; if not, see the table below
v=$(lightning --version 2>/dev/null | sed -n 's/^Lightning CLI version //p')
[ -n "$v" ] && [ "$(printf '%s\n' 2026.9.18 "$v" | sort -V | head -1)" = 2026.9.18 ]
|| uv pip install -U lightning-sdk || python3 -m pip install -U lightning-sdk lightning --version # must print "Lightning CLI version …"; if not, see the table below
|| uv pip install -U lightning-sdk || python3 -m pip install -U lightning-sdk lightning --version # must print "Lightning CLI version …"; if not, see the table below
sandbox <cmd>
is also installed standalone == lightning sandbox <cmd>
sandbox <cmd>lightning sandbox <cmd>sandbox <cmd>
is also installed standalone == lightning sandbox <cmd>
sandbox <cmd>lightning sandbox <cmd>
This uses, and if needed installs into, the environment the agent runs in (the user's project
venv, a conda env, …). Then call plain `lightning …` everywhere. If setup doesn't go cleanly:
| Symptom | Fix |
|---|---|
| Both installs fail: no active env, or pip refuses with `externally-managed-environment` | Install it on its own instead: `uv tool install lightning-sdk` (or `pipx install lightning-sdk`), then call `"$(uv tool dir --bin)/lightning"` if that dir isn't on `PATH` |
| `lightning --version` still prints no `Lightning CLI version` line after installing | `command -v lightning` shows which one runs. Another tool owns the name (PyTorch Lightning also installs a `lightning` command), or the env you installed into isn't on `PATH`: activate it (`source .venv/bin/activate`) or call its `bin/lightning` by full path |
| `No such command`, `No such option` or `unexpected extra argument` | The CLI is older than this skill expects: `uv pip install -U lightning-sdk` (or `pip install -U lightning-sdk`) in the env `command -v lightning` points into; `uv tool upgrade lightning-sdk` for a uv tool install |
| The upgrade fails on a version conflict with the project's own pins | Don't fight the pins: install it outside the project with `uv tool install lightning-sdk` and call `"$(uv tool dir --bin)/lightning"` |
| Installing is blocked (read-only env or home, agent sandbox) | Skip it and run each command as `UV_CACHE_DIR="${TMPDIR:-/tmp}/uv" uvx lightning-sdk …` |
| Every call fails on SSL/certificates, even `lightning --version` (`Could not find a suitable TLS CA certificate bundle`), only inside an agent sandbox | A `**/*.pem` read-deny rule is hiding certifi's public CA bundle (`site-packages/certifi/cacert.pem`). Allow that one path; don't disable the sandbox |
The install above also makes `lightning_sdk` importable in that env, so Python snippets run with
its `python`. If the CLI came from a uv tool or `uvx` fallback instead, run one-off scripts with
`uv run --with lightning-sdk python script.py`. For code that stays in the user's project, ask,
then declare `lightning-sdk` as a dependency with the project's own tool (`uv add`, `poetry add`).
**Org scope comes from the API key — there is no org flag or `LIGHTNING_ORG_ID` env var (it's rejected).** Sandboxes need an **org- or teamspace-scoped API key** in `LIGHTNING_SANDBOX_API_KEY`; a personal `lightning login` credential fails with *"Use a teamspace- or org-scoped API key (Members → API keys), not your personal login key."*
You can mint an org-scoped key from the CLI (requires working personal auth):
```bash
export LIGHTNING_SANDBOX_API_KEY=$(lightning api-key create --org my-org --name sandbox-agent)
这会使用 Agent 运行所在的环境(用户的项目 venv、conda 环境等),如有需要也会安装到该环境中。之后所有地方都直接调用 `lightning …` 即可。如果安装过程不顺利,请参考下表:
| 症状 | 解决方法 |
|---|---|
| 两种安装方式都失败:没有激活的环境,或 pip 报错 `externally-managed-environment` | 改为单独安装:`uv tool install lightning-sdk`(或 `pipx install lightning-sdk`),如果该目录不在 `PATH` 中,则调用 `"$(uv tool dir --bin)/lightning"` |
| 安装后 `lightning --version` 仍不输出 `Lightning CLI version` 行 | 用 `command -v lightning` 查看运行的是哪个命令。可能是其他工具占用了这个名称(PyTorch Lightning 也会安装 `lightning` 命令),或者你安装的环境不在 `PATH` 中:激活该环境(`source .venv/bin/activate`)或通过完整路径调用其 `bin/lightning` |
| `No such command`、`No such option` 或 `unexpected extra argument` | CLI 版本低于本 Skill 要求:在 `command -v lightning` 指向的环境中执行 `uv pip install -U lightning-sdk`(或 `pip install -U lightning-sdk`);如果是 uv tool 安装的则执行 `uv tool upgrade lightning-sdk` |
| 升级因与项目自身的依赖版本冲突而失败 | 不要强行修改依赖:用 `uv tool install lightning-sdk` 安装到项目外部,并调用 `"$(uv tool dir --bin)/lightning"` |
| 安装被阻止(只读环境或 home 目录、Agent 沙箱) | 跳过安装,将每条命令改为 `UV_CACHE_DIR="${TMPDIR:-/tmp}/uv" uvx lightning-sdk …` 执行 |
| 即使是 `lightning --version` 也每次都因 SSL/证书失败(`Could not find a suitable TLS CA certificate bundle`),且仅在 Agent 沙箱内出现 | 是 `**/*.pem` 读取拒绝规则隐藏了 certifi 的公共 CA 包(`site-packages/certifi/cacert.pem`)。请允许该路径;不要禁用沙箱 |
上述安装操作还会让 `lightning_sdk` 在该环境中可导入,因此 Python 代码片段可以用该环境的 `python` 运行。如果 CLI 来自 uv tool 或 `uvx` 备用方案,则使用 `uv run --with lightning-sdk python script.py` 运行一次性脚本。对于要保留在用户项目中的代码,请先询问用户,然后使用项目自身的工具(`uv add`、`poetry add`)将 `lightning-sdk` 声明为依赖项。
**组织范围由 API 密钥决定——没有组织参数,也没有 `LIGHTNING_ORG_ID` 环境变量(会被拒绝)。** 沙箱需要在 `LIGHTNING_SANDBOX_API_KEY` 中配置**组织范围或 teamspace 范围的 API 密钥**;个人 `lightning login` 凭证会报错:*"Use a teamspace- or org-scoped API key (Members → API keys), not your personal login key."*
你可以通过 CLI 创建组织范围的密钥(需要有效的个人认证):
```bash
export LIGHTNING_SANDBOX_API_KEY=$(lightning api-key create --org my-org --name sandbox-agent)or reuse the org default key: lightning api-key get --org my-org
or reuse the org default key: lightning api-key get --org my-org
If the user belongs to multiple orgs and none is configured, **ask which org to use**:
```bash
lightning api /v1/memberships | jq -r '.memberships[] | select(.ownerType=="organization") | [.ownerId, .name] | @tsv'Snapshot/stop of persistent sandboxes needs a teamspace-scoped key (org-scoped is not enough).
如果用户属于多个组织且未配置任何组织,**请询问要使用哪个组织**:
```bash
lightning api /v1/memberships | jq -r '.memberships[] | select(.ownerType=="organization") | [.ownerId, .name] | @tsv'持久化沙箱的快照/停止操作需要 teamspace 范围的密钥(组织范围的不够)。
CLI reference
CLI 参考
bash
undefinedbash
undefinedcreate — blocks until running (usually seconds)
create — blocks until running (usually seconds)
lightning sandbox create --name devbox
[--instance-type cpu-1] # default cpu-1
[--runtime python313] # DEFAULT IS node24 (Node.js, NO python!) — use python313 for Python
# node22 | node24 | python313, each with a -docker variant
[--image ghcr.io/org/img:latest] # custom rootfs, CPU-only; mutually exclusive with --runtime
[--image-secret-ref <docker-registry-secret>]
[--docker] # dockerd at boot; == appending -docker to --runtime
[--teamspace owner/teamspace] [--persistent] [--spot] [--port 8000]
[--snapshot-id snap-...] # warm start from a snapshot
[--timeout 3600000] # auto-stop lifetime in MILLISECONDS
[--json] # prints the sandbox id — capture it for later commands
[--instance-type cpu-1] # default cpu-1
[--runtime python313] # DEFAULT IS node24 (Node.js, NO python!) — use python313 for Python
# node22 | node24 | python313, each with a -docker variant
[--image ghcr.io/org/img:latest] # custom rootfs, CPU-only; mutually exclusive with --runtime
[--image-secret-ref <docker-registry-secret>]
[--docker] # dockerd at boot; == appending -docker to --runtime
[--teamspace owner/teamspace] [--persistent] [--spot] [--port 8000]
[--snapshot-id snap-...] # warm start from a snapshot
[--timeout 3600000] # auto-stop lifetime in MILLISECONDS
[--json] # prints the sandbox id — capture it for later commands
lightning sandbox list [--teamspace owner/teamspace] [--limit N] [--json]
lightning sandbox create --name devbox
[--instance-type cpu-1] # default cpu-1
[--runtime python313] # DEFAULT IS node24 (Node.js, NO python!) — use python313 for Python
# node22 | node24 | python313, each with a -docker variant
[--image ghcr.io/org/img:latest] # custom rootfs, CPU-only; mutually exclusive with --runtime
[--image-secret-ref <docker-registry-secret>]
[--docker] # dockerd at boot; == appending -docker to --runtime
[--teamspace owner/teamspace] [--persistent] [--spot] [--port 8000]
[--snapshot-id snap-...] # warm start from a snapshot
[--timeout 3600000] # auto-stop lifetime in MILLISECONDS
[--json] # prints the sandbox id — capture it for later commands
[--instance-type cpu-1] # default cpu-1
[--runtime python313] # DEFAULT IS node24 (Node.js, NO python!) — use python313 for Python
# node22 | node24 | python313, each with a -docker variant
[--image ghcr.io/org/img:latest] # custom rootfs, CPU-only; mutually exclusive with --runtime
[--image-secret-ref <docker-registry-secret>]
[--docker] # dockerd at boot; == appending -docker to --runtime
[--teamspace owner/teamspace] [--persistent] [--spot] [--port 8000]
[--snapshot-id snap-...] # warm start from a snapshot
[--timeout 3600000] # auto-stop lifetime in MILLISECONDS
[--json] # prints the sandbox id — capture it for later commands
lightning sandbox list [--teamspace owner/teamspace] [--limit N] [--json]
run a command (use -- before the command); CLI exits with the command's exit code
run a command (use -- before the command); CLI exits with the command's exit code
lightning sandbox run <SANDBOX_ID> [--cwd /workspace] [--env KEY=VALUE] -- python -c "print('hi')"
lightning sandbox run <SANDBOX_ID> --detached -- bash -lc "long-task" # prints cmd_id
lightning sandbox command <SANDBOX_ID> <COMMAND_ID> # status + output
lightning sandbox logs <SANDBOX_ID> <COMMAND_ID>
lightning sandbox commands <SANDBOX_ID> # history
lightning sandbox run <SANDBOX_ID> [--cwd /workspace] [--env KEY=VALUE] -- python -c "print('hi')"
lightning sandbox run <SANDBOX_ID> --detached -- bash -lc "long-task" # prints cmd_id
lightning sandbox command <SANDBOX_ID> <COMMAND_ID> # status + output
lightning sandbox logs <SANDBOX_ID> <COMMAND_ID>
lightning sandbox commands <SANDBOX_ID> # history
lifecycle
lifecycle
lightning sandbox stop <SANDBOX_ID> # persistent: auto-snapshot + pause; ephemeral: == delete
lightning sandbox start <SANDBOX_ID> # resume a stopped persistent sandbox
lightning sandbox delete <SANDBOX_ID> -y # destroys sandbox AND its auto-snapshot; -y required non-interactively
lightning sandbox stop <SANDBOX_ID> # persistent: auto-snapshot + pause; ephemeral: == delete
lightning sandbox start <SANDBOX_ID> # resume a stopped persistent sandbox
lightning sandbox delete <SANDBOX_ID> -y # destroys sandbox AND its auto-snapshot; -y required non-interactively
snapshots (filesystem only — running processes are not preserved)
snapshots (filesystem only — running processes are not preserved)
lightning sandbox snapshot create <SANDBOX_ID> [--expiration <MS>] [--exclude PATH]
lightning sandbox snapshot list [--name N] [--teamspace owner/teamspace]
lightning sandbox snapshot get <SNAPSHOT_ID>
lightning sandbox snapshot delete <SNAPSHOT_ID> -y
There is no `cp`/upload CLI — move files via `run` with shell commands, or the SDK file API below.lightning sandbox snapshot create <SANDBOX_ID> [--expiration <MS>] [--exclude PATH]
lightning sandbox snapshot list [--name N] [--teamspace owner/teamspace]
lightning sandbox snapshot get <SNAPSHOT_ID>
lightning sandbox snapshot delete <SNAPSHOT_ID> -y
没有 `cp`/上传 CLI——请通过带 shell 命令的 `run` 或下面的 SDK 文件 API 来传输文件。Python SDK
Python SDK
python
from lightning_sdk.sandbox import Sandbox, SandboxConfig, RunCommandOpts, NetworkPolicy, PtyCreateOptspython
from lightning_sdk.sandbox import Sandbox, SandboxConfig, RunCommandOpts, NetworkPolicy, PtyCreateOptsoptional explicit config; otherwise env (LIGHTNING_SANDBOX_API_KEY) / lightning login creds are used
optional explicit config; otherwise env (LIGHTNING_SANDBOX_API_KEY) / lightning login creds are used
Sandbox.configure(api_key="...")
sb = Sandbox.create(
name="devbox",
instance_type="cpu-1",
runtime="python313", # default is node24 (Node.js only — no python!)
teamspace="owner/teamspace",
persistent=True, # enables stop()/resume()
docker=True, # dockerd at boot; see "Docker inside a sandbox"
ports=[8080], # exposes public HTTPS URLs for these ports
network_policy=NetworkPolicy(allow_cidrs=["10.0.0.0/8"]), # or "deny-all" / default open egress
timeout=30 * 60 * 1000, # auto-stop, MILLISECONDS
) # blocks until running
Sandbox.configure(api_key="...")
sb = Sandbox.create(
name="devbox",
instance_type="cpu-1",
runtime="python313", # default is node24 (Node.js only — no python!)
teamspace="owner/teamspace",
persistent=True, # enables stop()/resume()
docker=True, # dockerd at boot; see "Docker inside a sandbox"
ports=[8080], # exposes public HTTPS URLs for these ports
network_policy=NetworkPolicy(allow_cidrs=["10.0.0.0/8"]), # or "deny-all" / default open egress
timeout=30 * 60 * 1000, # auto-stop, MILLISECONDS
) # blocks until running
commands — non-detached blocks until exit
commands — non-detached blocks until exit
cmd = sb.run_command("python -c 'print(42)'")
print(cmd.exit_code, cmd.output) # output = combined stdout+stderr
bg = sb.run_command(RunCommandOpts(cmd="python", args=["train.py"], cwd="/workspace",
env={"MODE": "test"}, detached=True))
bg.wait(timeout=600); print(bg.output) # or sb.kill_command(bg.cmd_id)
cmd = sb.run_command("python -c 'print(42)'")
print(cmd.exit_code, cmd.output) # output = combined stdout+stderr
bg = sb.run_command(RunCommandOpts(cmd="python", args=["train.py"], cwd="/workspace",
env={"MODE": "test"}, detached=True))
bg.wait(timeout=600); print(bg.output) # or sb.kill_command(bg.cmd_id)
files — content strings via REST; no host<->sandbox copy helper
files — content strings via REST; no host<->sandbox copy helper
sb.write_file("/workspace/app.py", "print('hi')")
text = sb.read_file("/workspace/out.txt") # None if missing
sb.fs.mkdir("/workspace/data", recursive=True)
sb.fs.exists("/workspace/app.py"); sb.fs.readdir("/workspace"); sb.fs.rm("/tmp/x", recursive=True)
sb.write_file("/workspace/app.py", "print('hi')")
text = sb.read_file("/workspace/out.txt") # None if missing
sb.fs.mkdir("/workspace/data", recursive=True)
sb.fs.exists("/workspace/app.py"); sb.fs.readdir("/workspace"); sb.fs.rm("/tmp/x", recursive=True)
exposed ports (only those passed as ports=[...] at create) — proxied public HTTPS
exposed ports (only those passed as ports=[...] at create) — proxied public HTTPS
sb.port_urls # {"8080": "https://8080-<sandbox-id>-s.cloudspaces.litng.ai"}
sb.get_port_url(8080) # ValueError if 8080 wasn't exposed at create
sb.port_urls # {"8080": "https://8080-<sandbox-id>-s.cloudspaces.litng.ai"}
sb.get_port_url(8080) # ValueError if 8080 wasn't exposed at create
normally populated by create; if empty, re-get: Sandbox().get(sb.sandbox_id).port_urls
normally populated by create; if empty, re-get: Sandbox().get(sb.sandbox_id).port_urls
lifecycle
lifecycle
sb.extend_timeout(10 * 60 * 1000) # heartbeat; milliseconds, min 1000
snap = sb.snapshot() # filesystem snapshot; later: Sandbox.create(snapshot_id=snap.id)
auto_snap_id = sb.stop() # persistent only; sb.resume() brings it back with same id
sb.delete() # ALWAYS clean up — GC does not delete remote sandboxes
sb.extend_timeout(10 * 60 * 1000) # heartbeat; milliseconds, min 1000
snap = sb.snapshot() # filesystem snapshot; later: Sandbox.create(snapshot_id=snap.id)
auto_snap_id = sb.stop() # persistent only; sb.resume() brings it back with same id
sb.delete() # ALWAYS clean up — GC does not delete remote sandboxes
find existing
find existing
client = Sandbox()
for s in client.list(teamspace="owner/teamspace").sandboxes: print(s.sandbox_id, s.status)
sb = client.get("sbx-...")
Interactive PTY (`websocket-client` ships with the SDK): `sb.process.create_pty(PtyCreateOpts(session_name="main"))` → `pty.send_input("ls\n")`, `pty.wait()`. The result's `exit_code` is the shell's real status on a clean close, `0` when the backend reports none, `-1` if the connection broke (`error` says why) and `None` while running — prefer `run_command` when you need a guaranteed exit code.client = Sandbox()
for s in client.list(teamspace="owner/teamspace").sandboxes: print(s.sandbox_id, s.status)
sb = client.get("sbx-...")
交互式 PTY(SDK 自带 `websocket-client`):`sb.process.create_pty(PtyCreateOpts(session_name="main"))` → `pty.send_input("ls\n")`、`pty.wait()`。结果中的 `exit_code` 在正常关闭时是 shell 的真实状态,后端未返回时为 `0`,连接断开时为 `-1`(`error` 字段会说明原因),运行中为 `None`——如果你需要有保证的退出码,请优先使用 `run_command`。Docker inside a sandbox
沙箱内的 Docker
The runtimes ship Docker (engine, CLI, buildx, compose) with already running by the time create returns — nothing to install, no daemon to bootstrap, works immediately. Pick the variant explicitly, or use / to append the suffix to the base runtime you asked for:
-dockerdockerddocker version--dockerdocker=Truebash
lightning sandbox create --runtime python313-docker --port 8080 --json # cpu-1 default is fine for Docker
lightning sandbox create --runtime python313 --docker # identical — resolves to python313-docker
lightning sandbox create --docker # no runtime -> node24-docker (Node, NOT Python)Variants: , , ; anything else fails with . is rejected together with (a custom image opts in itself by carrying the OCI label ) or (the runtime comes from the snapshot).
node22-dockernode24-dockerpython313-dockerinvalid runtime: <id>docker=Trueimageai.lightning.sandbox.docker=truesnapshot_id带 后缀的运行时内置了 Docker(引擎、CLI、buildx、compose),且创建返回时 已经在运行——无需安装,无需启动守护进程, 可立即使用。你可以显式选择该变体,或者使用 / 为你指定的基础运行时追加该后缀:
-dockerdockerddocker version--dockerdocker=Truebash
lightning sandbox create --runtime python313-docker --port 8080 --json # cpu-1 default is fine for Docker
lightning sandbox create --runtime python313 --docker # identical — resolves to python313-docker
lightning sandbox create --docker # no runtime -> node24-docker (Node, NOT Python)可用变体:、、;其他任何值都会报错 。 不能与 (自定义镜像通过携带 OCI 标签 自行启用 Docker)或 (运行时来自快照)同时使用。
node22-dockernode24-dockerpython313-dockerinvalid runtime: <id>docker=Trueimageai.lightning.sandbox.docker=truesnapshot_idWhere images are stored, and how much room you get
镜像存储位置与可用空间
Pick the instance type for where lands, not for its RAM: and keep images on disk, every other shape keeps them in RAM. That makes the default a usable Docker box — a 1.1 GB image pulls fine on a sandbox with 1.25 GiB of RAM, because the image never touches memory — while the larger gives you more RAM but less image room.
/var/lib/dockercpu-1cpu-4cpu-1cpu-2 | RAM | | image room | |
|---|---|---|---|---|
| 1.25 GiB | disk | 5 GB | yes |
| 8.75 GiB | RAM (tmpfs) | 4.4 GB | no |
| 18.75 GiB | disk | 40 GB | yes |
| 38.75 GiB | RAM (tmpfs) | 20 GB | no |
| 77.5 GiB | RAM (tmpfs) | 39 GB | no |
Those are the current defaults, measured; treat them as a planning guide and confirm the live number with before sizing a pull.
df -h /var/lib/docker- On the disk shapes there is one quota for everything — ,
/and/tmpdraw on the same pool, so a 3 GB file in/var/lib/dockerleaves 3 GB less for images. Raise it with the SDK-only/root(storage_gbgives docker 20 GB); there is no CLI flag for it.Sandbox.create(..., instance_type="cpu-1", storage_gb=20) - On the RAM shapes the cap is half the sandbox's memory and those bytes count against your memory budget, so an image plus a hungry process can still push the sandbox into an out-of-memory kill. buys disk for
storage_gb, never image room./ - reports the real ceiling — trust it over any figure in this table. Older clusters report a large meaningless size instead: if you see hundreds of GB, nothing is bounding docker but the sandbox's own memory, and overrunning it kills the sandbox rather than failing the pull — keep images well under the RAM column.
df -h /var/lib/docker
Rules of thumb: for anything image-heavy on a budget, when you want both room (40 GB) and RAM for builds, when 5 GB is tight. Reach for / only when the workload itself needs the memory, and keep images small there.
cpu-1cpu-4storage_gbcpu-2cpu-8Running out of space is now an ordinary error rather than a fatality — a pull into a full data root fails with and the sandbox keeps running, so you can delete images and retry:
no space left on devicebash
lightning sandbox run $SBX -- bash -lc 'docker system df; docker image prune -af; df -h /var/lib/docker'选择实例类型时,应根据 的存储位置而非 RAM 大小来选: 和 将镜像存在磁盘上,其他所有规格都将镜像存在 RAM 中。 这使得默认的 成为可用的 Docker 环境——在 1.25 GiB RAM 的沙箱上拉取 1.1 GB 的镜像完全没问题,因为镜像不会占用内存——而更大的 虽然 RAM 更多,但镜像可用空间更小。
/var/lib/dockercpu-1cpu-4cpu-1cpu-2 | RAM | | 镜像可用空间 | |
|---|---|---|---|---|
| 1.25 GiB | 磁盘 | 5 GB | 是 |
| 8.75 GiB | RAM (tmpfs) | 4.4 GB | 否 |
| 18.75 GiB | 磁盘 | 40 GB | 是 |
| 38.75 GiB | RAM (tmpfs) | 20 GB | 否 |
| 77.5 GiB | RAM (tmpfs) | 39 GB | 否 |
以上是当前的默认值,为实测数据;请将其作为规划参考,并在拉取大型镜像前用 确认实际可用空间。
df -h /var/lib/docker- 磁盘规格的所有存储共享一个配额——、
/和/tmp共用同一个存储池,因此/var/lib/docker中 3 GB 的文件会让镜像可用空间减少 3 GB。可通过仅 SDK 支持的/root参数扩容(storage_gb会给 Docker 分配 20 GB);CLI 没有对应的参数。Sandbox.create(..., instance_type="cpu-1", storage_gb=20) - RAM 规格的镜像空间上限为沙箱内存的一半,且这部分空间会占用内存预算,因此镜像加上内存占用高的进程仍可能导致沙箱因内存不足被终止。只会为
storage_gb增加磁盘空间,不会增加镜像可用空间。/ - 显示的是真实上限——请以它为准,不要完全依赖本表中的数据。较旧的集群会返回一个无意义的大数值:如果你看到几百 GB 的空间,说明 Docker 没有额外限制,仅受沙箱自身内存约束,超出时会直接终止沙箱而不是拉取失败——请确保镜像大小远小于 RAM 列的数值。
df -h /var/lib/docker
经验法则: 预算有限且镜像较大时选 ;同时需要大镜像空间(40 GB)和足够 RAM 进行构建时选 ;5 GB 空间紧张时用 扩容。仅当工作负载本身需要大内存时才选择 /,且请尽量保持镜像较小。
cpu-1cpu-4storage_gbcpu-2cpu-8空间不足现在是普通错误而非致命错误——向已满的数据根目录拉取镜像会报错 ,且沙箱会继续运行,因此你可以删除镜像后重试:
no space left on devicebash
lightning sandbox run $SBX -- bash -lc 'docker system df; docker image prune -af; df -h /var/lib/docker'Networking — the part you must adapt
网络——你必须适配的部分
dockerd--bridge=none --iptables=false --ip6tables=falsehostnonedocker network ls- Run containers with . Without it a container has no network at all — DNS fails (
--network=host). Image pulls still work either way, since dockerd itself sits on the sandbox's netstack.wget: bad address - Build with (compose:
--network=host), or everybuild: {context: ., network: host}step dies withRUN.failed to solve: ... network bridge not found - Container→container over , never a compose service name — host networking means no bridge DNS, so
127.0.0.1:<port>ordbdies withapi. Plaingaierror: [Errno -2] Name or service not knownresolves fine; it is the service names that don't exist.localhost - is silently ignored — port publishing belongs to the bridge, and host networking has none. The container is already on the sandbox's netstack, so the process inside must listen on the port you want (
-p 8080:80configured for 8080,nginx); remapping it from the outside is not possible.uvicorn --port 8080exits 0 and serves nothing.docker run -p - A host-networked container listening on is what the sandbox's public URL for 8080 serves — declare
:8080/--port 8080at create, thenports=[8080].sb.get_port_url(8080)
Compose template that works as-is (FastAPI + Redis; run detached with a generous timeout, since builds pull layers):
docker compose up -d --buildyaml
services:
web:
build: {context: ., network: host} # host net so pip install reaches PyPI
network_mode: host
environment: [REDIS_HOST=127.0.0.1] # NOT "redis" — no bridge DNS
depends_on: [redis]
redis:
image: redis:7-alpine
network_mode: hostdockerd--bridge=none --iptables=false --ip6tables=falsehostnonedocker network ls- 运行容器时请使用 。 不加该参数的话容器完全没有网络——DNS 会失败(
--network=host)。镜像拉取两种方式都可以,因为 dockerd 本身运行在沙箱的网络栈中。wget: bad address - 构建镜像时请使用 (compose 中:
--network=host),否则每个build: {context: ., network: host}步骤都会报错RUN。failed to solve: ... network bridge not found - 容器之间通过 通信,不要使用 compose 服务名——主机网络模式下没有网桥 DNS,因此
127.0.0.1:<端口>或db这类名称会报错api。普通的gaierror: [Errno -2] Name or service not known可以正常解析;不存在的是服务名称。localhost - 会被静默忽略——端口发布属于网桥的功能,主机网络模式下没有网桥。容器已经在沙箱的网络栈中,因此容器内的进程必须监听你想要的端口(
-p 8080:80配置为 8080、nginx);无法从外部重新映射端口。uvicorn --port 8080会以 0 退出,但不会提供任何服务。docker run -p - 监听 的主机网络容器,其服务会通过沙箱的 8080 公共 URL 对外提供——创建时声明
:8080/--port 8080,然后调用ports=[8080]即可。sb.get_port_url(8080)
可直接使用的 Compose 模板(FastAPI + Redis;请以分离模式运行 ,并设置较长的超时时间,因为构建过程会拉取镜像层):
docker compose up -d --buildyaml
services:
web:
build: {context: ., network: host} # host net so pip install reaches PyPI
network_mode: host
environment: [REDIS_HOST=127.0.0.1] # NOT "redis" — no bridge DNS
depends_on: [redis]
redis:
image: redis:7-alpine
network_mode: hostDocker gotchas
Docker 常见坑点
- Where images live depends on the instance type — disk on /
cpu-1, RAM everywhere else — and it decides both your ceiling and whethercpu-4helps. See Where images are stored; getting this wrong is the difference between a 5 GB budget and a 4.4 GB one that also competes with your processes.storage_gb - A full data root fails the pull, it no longer kills the sandbox. Both backings return and stay up. If you are on an older cluster you may still hit the historical behaviour, where the sandbox was terminated and every later call returned
no space left on device— if you see that, you overran the data root, so drop to a smaller image or move to429 sandbox terminated: out of memory/cpu-1.cpu-4 - Restricted egress and image pulls don't mix. Under dockerd still starts, but every pull fails after a long stall with
network_policy="deny-all". A CIDR allowlist doesn't rescue it: allowlisting the resolvers (Get "https://registry-1.docker.io/v2/": context deadline exceeded,1.1.1.1/32, see the DNS gotcha below) does fix name resolution, and the pull then dies waiting on registry IPs you would have to enumerate — which Docker Hub serves from a shifting CDN. Bake the images into a custom image, or pull under the default open egress.8.8.8.8/32 - Docker Engine is pinned to v27 (shows the exact build) and v28+ is known-broken in this environment — don't upgrade it in-sandbox, it is unsupported. Docker is CPU-sandbox only, never GPU.
docker info - On a plain runtime, and
dockerare absent anddockerdreturnsmount, so you cannot add Docker after the fact — choose apermission deniedruntime at create time.-docker - There is no field on the REST API. If you drive
dockerdirectly, send/v1/core/sandboxes."runtime": "node24-docker"
- 镜像存储位置取决于实例类型——/
cpu-1存在磁盘上,其他规格存在 RAM 中——这决定了你的空间上限以及cpu-4是否有用。参见镜像存储位置与可用空间;搞错这一点的话,你可能以为有 5 GB 预算,实际只有 4.4 GB 还要和进程共享内存。storage_gb - 数据根目录满了只会导致拉取失败,不会再终止沙箱。 两种存储方式都会返回 ,且沙箱保持运行。如果你使用的是较旧的集群,可能仍会遇到旧行为:沙箱被终止,后续所有调用都返回
no space left on device——如果看到这个错误,说明你超出了数据根目录的空间,请换用更小的镜像或迁移到429 sandbox terminated: out of memory/cpu-1规格。cpu-4 - 受限出口策略和镜像拉取不能共存。 在 下,dockerd 仍会启动,但每次拉取都会在长时间卡顿后报错
network_policy="deny-all"。CIDR 白名单也解决不了:将解析器(Get "https://registry-1.docker.io/v2/": context deadline exceeded、1.1.1.1/32,参见下面的 DNS 坑点)加入白名单确实能修复域名解析,但拉取会卡在等待注册表 IP 上——而 Docker Hub 的 IP 由动态 CDN 提供,无法枚举。请将镜像打包到自定义镜像中,或者在默认开放出口的环境下拉取。8.8.8.8/32 - Docker Engine 固定为 v27(可通过 查看具体构建版本),v28+ 在此环境中已知有问题——不要在沙箱内升级,不支持该操作。Docker 仅支持 CPU 沙箱,不支持 GPU。
docker info - 在普通运行时中,和
docker完全不存在,且dockerd命令会返回mount,因此你无法事后添加 Docker——请在创建时选择permission denied运行时。-docker - REST API 上没有 字段。如果你直接调用
docker,请传入/v1/core/sandboxes。"runtime": "node24-docker"
Example workflows
示例工作流
Prompts this skill handles: "run this untrusted script somewhere safe", "test my code in a clean VM", "spin up a container from ghcr.io/... and poke around", "give me a devbox that survives restarts".
Safely execute untrusted/generated code (no network egress, auto-cleanup):
python
from lightning_sdk.sandbox import Sandbox
sb = Sandbox.create(name="quarantine", teamspace="my-org/my-teamspace", runtime="python313",
network_policy="deny-all", timeout=15 * 60 * 1000) # hard kill after 15 min
try:
sb.write_file("/workspace/suspect.py", open("suspect.py").read())
cmd = sb.run_command("python /workspace/suspect.py")
print(cmd.exit_code, cmd.output)
finally:
sb.delete()Test code in a clean environment from the CLI:
bash
SBX=$(lightning sandbox create --name test-run --teamspace my-org/my-teamspace --runtime python313 --timeout 1800000 --json | jq -r .id)
lightning sandbox run $SBX -- python --version
lightning sandbox run $SBX --cwd /workspace -- bash -lc "pip install requests && python -c 'import requests; print(requests.__version__)'"
lightning sandbox run $SBX --detached -- bash -lc "pytest -q > /workspace/test.log 2>&1" # prints cmd_id
lightning sandbox command $SBX <cmd_id> # poll status + output
lightning sandbox delete $SBX -yRun a containerized app and preview it on a public URL:
bash
SBX=$(lightning sandbox create --name preview --runtime python313-docker \
--port 8080 --timeout 1800000 --json | jq -r .id) # cpu-1 default: images go to disk本 Skill 可处理的提示词:"在安全的地方运行这个不可信的脚本"、"在干净的 VM 中测试我的代码"、"从 ghcr.io/... 启动一个容器并探索一下"、"给我一个重启后还能保留的开发箱"。
安全执行不可信/生成的代码(无网络出口、自动清理):
python
from lightning_sdk.sandbox import Sandbox
sb = Sandbox.create(name="quarantine", teamspace="my-org/my-teamspace", runtime="python313",
network_policy="deny-all", timeout=15 * 60 * 1000) # hard kill after 15 min
try:
sb.write_file("/workspace/suspect.py", open("suspect.py").read())
cmd = sb.run_command("python /workspace/suspect.py")
print(cmd.exit_code, cmd.output)
finally:
sb.delete()通过 CLI 在干净环境中测试代码:
bash
SBX=$(lightning sandbox create --name test-run --teamspace my-org/my-teamspace --runtime python313 --timeout 1800000 --json | jq -r .id)
lightning sandbox run $SBX -- python --version
lightning sandbox run $SBX --cwd /workspace -- bash -lc "pip install requests && python -c 'import requests; print(requests.__version__)'"
lightning sandbox run $SBX --detached -- bash -lc "pytest -q > /workspace/test.log 2>&1" # prints cmd_id
lightning sandbox command $SBX <cmd_id> # poll status + output
lightning sandbox delete $SBX -y运行容器化应用并通过公共 URL 预览:
bash
SBX=$(lightning sandbox create --name preview --runtime python313-docker \
--port 8080 --timeout 1800000 --json | jq -r .id) # cpu-1 default: images go to disk--network=host is mandatory, and the container must LISTEN on 8080 (-p is ignored)
--network=host is mandatory, and the container must LISTEN on 8080 (-p is ignored)
lightning sandbox run $SBX -- docker run -d --network=host --name web
-v /workspace:/srv -w /srv python:3.13-alpine python -m http.server 8080
-v /workspace:/srv -w /srv python:3.13-alpine python -m http.server 8080
lightning sandbox run $SBX -- curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080
lightning sandbox list --json | jq -r ".sandboxes[] | select(.id=="$SBX") | .port_urls["8080"]"
lightning sandbox delete $SBX -y
**Try out a custom image:**
```bash
lightning sandbox create --name img-test --image ghcr.io/myorg/myimage:latest \
--teamspace my-org/my-teamspace --timeout 1800000lightning sandbox run $SBX -- docker run -d --network=host --name web
-v /workspace:/srv -w /srv python:3.13-alpine python -m http.server 8080
-v /workspace:/srv -w /srv python:3.13-alpine python -m http.server 8080
lightning sandbox run $SBX -- curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080
lightning sandbox list --json | jq -r ".sandboxes[] | select(.id=="$SBX") | .port_urls["8080"]"
lightning sandbox delete $SBX -y
**试用自定义镜像:**
```bash
lightning sandbox create --name img-test --image ghcr.io/myorg/myimage:latest \
--teamspace my-org/my-teamspace --timeout 1800000private registry: --image-secret-ref <docker-registry-secret-name>
private registry: --image-secret-ref <docker-registry-secret-name>
**Persistent devbox with snapshot-based branching:**
```python
sb = Sandbox.create(name="devbox", teamspace="my-org/my-teamspace", runtime="python313", persistent=True)
sb.run_command("pip install torch numpy pandas") # slow setup, do once
snap = sb.snapshot() # golden image
sb.stop() # pause billing; sb.resume() later, same id
fresh = Sandbox.create(name="experiment-1", snapshot_id=snap.id,
teamspace="my-org/my-teamspace") # warm clone with deps preinstalled
**支持快照分支的持久化开发箱:**
```python
sb = Sandbox.create(name="devbox", teamspace="my-org/my-teamspace", runtime="python313", persistent=True)
sb.run_command("pip install torch numpy pandas") # slow setup, do once
snap = sb.snapshot() # golden image
sb.stop() # pause billing; sb.resume() later, same id
fresh = Sandbox.create(name="experiment-1", snapshot_id=snap.id,
teamspace="my-org/my-teamspace") # warm clone with deps preinstalledRaw API fallback
原始 API 备用方案
bash
lightning api /v1/core/sandboxes -X GET -f "organizationId=${ORG_ID}" -f "projectId=${PROJECT_ID}" -f limit=20
lightning api /v1/core/sandboxes -X GET ... | jq -r '.sandboxes[] | .name // .id'
lightning api "/v1/core/sandboxes/${SANDBOX_ID}" -X GET -f "organizationId=${ORG_ID}" # -X GET: fields without it send a POST
lightning api "/v1/core/sandboxes/${SANDBOX_ID}/commands" -X POST -f command=ls -F detached=falseORG_IDlightning api /v1/memberships | jq -r '[.memberships[] | select(.ownerType == "organization") | .ownerId][0]'bash
lightning api /v1/core/sandboxes -X GET -f "organizationId=${ORG_ID}" -f "projectId=${PROJECT_ID}" -f limit=20
lightning api /v1/core/sandboxes -X GET ... | jq -r '.sandboxes[] | .name // .id'
lightning api "/v1/core/sandboxes/${SANDBOX_ID}" -X GET -f "organizationId=${ORG_ID}" # -X GET: fields without it send a POST
lightning api "/v1/core/sandboxes/${SANDBOX_ID}/commands" -X POST -f command=ls -F detached=false从成员关系中获取 :。
ORG_IDlightning api /v1/memberships | jq -r '[.memberships[] | select(.ownerType == "organization") | .ownerId][0]'Gotchas
注意事项
- Timeout units differ: /
create --timeout/ snapshotextend_timeout()are milliseconds;--expiration(detached wait) is seconds.sandbox run --timeout - Sandboxes keep billing until stopped/deleted and are not cleaned up by garbage collection — always /
stop(), and set a create-timedelete()as a safety net.timeout - and
sandbox deleteprompt for confirmation — passsandbox snapshot delete/-ynon-interactively. Without it they read the prompt from a closed stdin, print--yesand exit without deleting. Given the point above, a cleanup step that silently aborts leaves the sandbox billing indefinitely — this is the single easiest way to leak money here.Are you sure you want to delete? [y/N]: Aborted. - A CIDR allowlist does not implicitly permit DNS. is enforced at the IP layer, and the sandbox's
allow_cidrspoints at/etc/resolv.confand1.1.1.1— outside any realistic application allowlist — so every hostname lookup fails with8.8.8.8while raw-IP connections work. Include the resolver addresses (Temporary failure in name resolution,1.1.1.1/32) in the allowlist, or point the sandbox at a resolver inside it.8.8.8.8/32 - Files restored from a snapshot come back with mtime . Epoch-zero timestamps break
1970-01-01T00:00:00Z,make, and pip/setuptools staleness checks — which bites hardest in the pre-baked-environment use case snapshots exist for. Touch files you depend on, or avoid mtime-based staleness logic in a restored sandbox.ccache - Egress policy is Python-SDK-only. has no network-policy flag, so
sandbox createand CIDR allowlists require dropping intodeny-all; everything else here (create, run, snapshot, list, delete) is CLI-doable.lightning_sdk - There is no cost surface for sandboxes. ,
/v1/billing/usageand/v1/projects/<pid>/usageall 404, no CLI reports spend, and sandbox instance types (/v1/core/sandboxes/<id>/usage,cpu-1) don't appear in the priced accelerator catalog (or incpu-2) — so a sandbox run cannot be priced, even by hand. Budget with a create-timelightning machine listrather than by measuring after.timeout - Ephemeral (default) sandboxes lose everything on stop; only gives stop/resume. Snapshots capture the filesystem only, never running processes.
persistent=True - The default runtime is — Node.js only, no Python. Pass
node24/runtime="python313"for Python workloads (naming:--runtime python313,node22,node24, plus thepython313variants; invalid ids fail with "invalid runtime").-docker(custom rootfs) is CPU/gVisor-only and mutually exclusive withimage; private images needruntimepointing at a Docker-registry secret.image_secret_ref - To run containers inside a sandbox, use a runtime (
-docker) or--runtime python313-docker/docker=True— never hand-install Docker on a plain runtime. See Docker inside a sandbox, especially the--dockerrequirement.--network=host - Public port URLs only exist for ports declared at create time (/
ports=[8080]); there is no way to expose a port later.--port 8080normally returns them already populated increate; if empty, re-port_urlsthe sandbox.get - Network policy is create-time only — you cannot change egress rules on a running sandbox. Default is open egress (); use
allow-allor CIDR allowlists for untrusted code."deny-all" - Commands run as root inside the sandbox.
- Scoped-key errors: the CLI and SDK turn the raw server errors into hints. (raw: "organization_id is required") → you're on a personal login key.
Use a teamspace- or org-scoped API key ...(raw: "API key is not authorized for this project") → the key is bound to a different teamspace.Your teamspace-scoped API key is not authorized for the project requested via teamspace= ...→ snapshot/stop with an org-scoped key. Only rawThis operation requires a teamspace-scoped API key ...calls show the raw wording.lightning api
- 超时时间单位不统一: /
create --timeout/ 快照extend_timeout()的单位是毫秒;--expiration(分离模式等待)的单位是秒。sandbox run --timeout - 沙箱在停止/删除前会持续计费,且不会被垃圾回收清理——请务必调用 /
stop(),并在创建时设置delete()作为安全兜底。timeout - 和
sandbox delete会提示确认——非交互式调用时请传入sandbox snapshot delete/-y。 不加该参数的话,它们会从已关闭的标准输入读取提示,打印--yes然后不执行删除就退出。结合上一点,静默中止的清理步骤会导致沙箱持续计费——这是最容易产生意外费用的原因。Are you sure you want to delete? [y/N]: Aborted. - CIDR 白名单不会隐式允许 DNS。 在 IP 层生效,而沙箱的
allow_cidrs指向/etc/resolv.conf和1.1.1.1——这些地址不在任何实际应用的白名单中——因此所有域名解析都会失败,报错8.8.8.8,但直接 IP 连接可以正常工作。请将解析器地址(Temporary failure in name resolution、1.1.1.1/32)加入白名单,或者将沙箱指向内部的解析器。8.8.8.8/32 - 从快照恢复的文件的 mtime 为 。 零时间戳会破坏
1970-01-01T00:00:00Z、make以及 pip/setuptools 的新鲜度检查——这在快照最常用的预构建环境场景中影响最大。请 touch 你依赖的文件,或者在恢复的沙箱中避免使用基于 mtime 的新鲜度判断逻辑。ccache - 出口策略仅 Python SDK 支持。 没有网络策略参数,因此
sandbox create和 CIDR 白名单需要使用deny-all;其他所有功能(创建、运行、快照、列表、删除)都可以通过 CLI 完成。lightning_sdk - 沙箱没有费用查询接口。 、
/v1/billing/usage和/v1/projects/<pid>/usage都返回 404,没有 CLI 可以查询消费,且沙箱实例类型(/v1/core/sandboxes/<id>/usage、cpu-1)不在定价的加速器目录中(也不在cpu-2中)——因此即使手动计算也无法得出沙箱运行的费用。请通过创建时的lightning machine list来控制预算,而不是事后统计。timeout - 临时(默认)沙箱在停止后会丢失所有数据;只有 才支持停止/恢复。快照仅捕获文件系统,不包含运行中的进程。
persistent=True - 默认运行时是 ——仅包含 Node.js,没有 Python。 对于 Python 工作负载,请传入
node24/runtime="python313"(命名规则:--runtime python313、node22、node24,以及带python313的变体;无效 ID 会报错 "invalid runtime")。-docker(自定义根文件系统)仅支持 CPU/gVisor,且与image互斥;私有镜像需要runtime指向 Docker 注册表密钥。image_secret_ref - 要在沙箱内运行容器,请使用 运行时(
-docker)或--runtime python313-docker/docker=True——切勿在普通运行时上手动安装 Docker。参见沙箱内的 Docker,特别是--docker的要求。--network=host - 公共端口 URL 仅对创建时声明的端口有效(/
ports=[8080]);无法后续暴露端口。--port 8080通常会返回已填充的create;如果为空,请重新port_urls沙箱信息。get - 网络策略仅创建时可设置——无法在运行中的沙箱上修改出口规则。默认是开放出口();对于不可信代码,请使用
allow-all或 CIDR 白名单。"deny-all" - 沙箱内的命令以 root 身份运行。
- 范围密钥错误:CLI 和 SDK 会将原始服务器错误转换为提示。(原始错误:"organization_id is required")→ 你使用的是个人登录密钥。
Use a teamspace- or org-scoped API key ...(原始错误:"API key is not authorized for this project")→ 该密钥绑定到了另一个 teamspace。Your teamspace-scoped API key is not authorized for the project requested via teamspace= ...→ 使用组织范围密钥执行快照/停止操作。只有原始This operation requires a teamspace-scoped API key ...调用会显示原始错误信息。lightning api