lightning-sandboxes

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Lightning AI Sandboxes

Lightning AI Sandboxes

A Sandbox is a fast-booting isolated VM for code execution. Ephemeral by default (
persistent=True
enables stop/resume via auto-snapshots). Import from the subpackage —
from lightning_sdk.sandbox import Sandbox
(the top-level
lightning_sdk.sandbox.py
_Sandbox
class is legacy; ignore it).
Sandbox 是一种启动快速、用于代码执行的隔离 VM。默认是临时的(
persistent=True
可通过自动快照启用停止/恢复功能)。请从子包导入 ——
from lightning_sdk.sandbox import Sandbox
(顶层的
lightning_sdk.sandbox.py
中的
_Sandbox
类是旧版实现,请忽略)。

Setup & auth (sandbox-specific)

安装与认证(沙箱专属)

bash
undefined
bash
undefined

Use 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
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

sandbox <cmd>
is also installed standalone ==
lightning sandbox <cmd>

sandbox <cmd>
is also installed standalone ==
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
undefined
bash
undefined

create — 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
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
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, PtyCreateOpts
python
from lightning_sdk.sandbox import Sandbox, SandboxConfig, RunCommandOpts, NetworkPolicy, PtyCreateOpts

optional 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
-docker
runtimes ship Docker (engine, CLI, buildx, compose) with
dockerd
already running
by the time create returns — nothing to install, no daemon to bootstrap,
docker version
works immediately. Pick the variant explicitly, or use
--docker
/
docker=True
to append the suffix to the base runtime you asked for:
bash
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:
node22-docker
,
node24-docker
,
python313-docker
; anything else fails with
invalid runtime: <id>
.
docker=True
is rejected together with
image
(a custom image opts in itself by carrying the OCI label
ai.lightning.sandbox.docker=true
) or
snapshot_id
(the runtime comes from the snapshot).
带
-docker
后缀的运行时内置了 Docker(引擎、CLI、buildx、compose),且创建返回时
dockerd
已经在运行
——无需安装,无需启动守护进程,
docker version
可立即使用。你可以显式选择该变体,或者使用
--docker
/
docker=True
为你指定的基础运行时追加该后缀:
bash
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)
可用变体:
node22-docker
、
node24-docker
、
python313-docker
;其他任何值都会报错
invalid runtime: <id>
。
docker=True
不能与
image
(自定义镜像通过携带 OCI 标签
ai.lightning.sandbox.docker=true
自行启用 Docker)或
snapshot_id
(运行时来自快照)同时使用。

Where images are stored, and how much room you get

镜像存储位置与可用空间

Pick the instance type for where
/var/lib/docker
lands, not for its RAM:
cpu-1
and
cpu-4
keep images on disk, every other shape keeps them in RAM.
That makes the default
cpu-1
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
cpu-2
gives you more RAM but less image room.
--instance-type
RAM
/var/lib/docker
image room
storage_gb
raises it?
cpu-1
(default)
1.25 GiBdisk5 GByes
cpu-2
8.75 GiBRAM (tmpfs)4.4 GBno
cpu-4
18.75 GiBdisk40 GByes
cpu-8
38.75 GiBRAM (tmpfs)20 GBno
cpu-16
77.5 GiBRAM (tmpfs)39 GBno
Those are the current defaults, measured; treat them as a planning guide and confirm the live number with
df -h /var/lib/docker
before sizing a pull.
  • On the disk shapes there is one quota for everything —
    /
    ,
    /tmp
    and
    /var/lib/docker
    draw on the same pool, so a 3 GB file in
    /root
    leaves 3 GB less for images. Raise it with the SDK-only
    storage_gb
    (
    Sandbox.create(..., instance_type="cpu-1", storage_gb=20)
    gives docker 20 GB); there is no CLI flag for it.
  • 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.
    storage_gb
    buys disk for
    /
    , never image room.
  • df -h /var/lib/docker
    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.
Rules of thumb:
cpu-1
for anything image-heavy on a budget,
cpu-4
when you want both room (40 GB) and RAM for builds,
storage_gb
when 5 GB is tight. Reach for
cpu-2
/
cpu-8
only when the workload itself needs the memory, and keep images small there.
Running out of space is now an ordinary error rather than a fatality — a pull into a full data root fails with
no space left on device
and the sandbox keeps running, so you can delete images and retry:
bash
lightning sandbox run $SBX -- bash -lc 'docker system df; docker image prune -af; df -h /var/lib/docker'
选择实例类型时,应根据
/var/lib/docker
的存储位置而非 RAM 大小来选:
cpu-1
和
cpu-4
将镜像存在磁盘上,其他所有规格都将镜像存在 RAM 中。
这使得默认的
cpu-1
成为可用的 Docker 环境——在 1.25 GiB RAM 的沙箱上拉取 1.1 GB 的镜像完全没问题,因为镜像不会占用内存——而更大的
cpu-2
虽然 RAM 更多,但镜像可用空间更小。
--instance-type
RAM
/var/lib/docker
镜像可用空间
storage_gb
能否扩容?
cpu-1
(默认)
1.25 GiB磁盘5 GB是
cpu-2
8.75 GiBRAM (tmpfs)4.4 GB否
cpu-4
18.75 GiB磁盘40 GB是
cpu-8
38.75 GiBRAM (tmpfs)20 GB否
cpu-16
77.5 GiBRAM (tmpfs)39 GB否
以上是当前的默认值,为实测数据;请将其作为规划参考,并在拉取大型镜像前用
df -h /var/lib/docker
确认实际可用空间。
  • 磁盘规格的所有存储共享一个配额——
    /
    、
    /tmp
    和
    /var/lib/docker
    共用同一个存储池,因此
    /root
    中 3 GB 的文件会让镜像可用空间减少 3 GB。可通过仅 SDK 支持的
    storage_gb
    参数扩容(
    Sandbox.create(..., instance_type="cpu-1", storage_gb=20)
    会给 Docker 分配 20 GB);CLI 没有对应的参数。
  • RAM 规格的镜像空间上限为沙箱内存的一半,且这部分空间会占用内存预算,因此镜像加上内存占用高的进程仍可能导致沙箱因内存不足被终止。
    storage_gb
    只会为
    /
    增加磁盘空间,不会增加镜像可用空间。
  • df -h /var/lib/docker
    显示的是真实上限
    ——请以它为准,不要完全依赖本表中的数据。较旧的集群会返回一个无意义的大数值:如果你看到几百 GB 的空间,说明 Docker 没有额外限制,仅受沙箱自身内存约束,超出时会直接终止沙箱而不是拉取失败——请确保镜像大小远小于 RAM 列的数值。
经验法则: 预算有限且镜像较大时选
cpu-1
;同时需要大镜像空间(40 GB)和足够 RAM 进行构建时选
cpu-4
;5 GB 空间紧张时用
storage_gb
扩容。仅当工作负载本身需要大内存时才选择
cpu-2
/
cpu-8
,且请尽量保持镜像较小。
空间不足现在是普通错误而非致命错误——向已满的数据根目录拉取镜像会报错
no space left on device
,且沙箱会继续运行,因此你可以删除镜像后重试:
bash
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
runs
--bridge=none --iptables=false --ip6tables=false
, so only the
host
and
none
docker networks exist (
docker network ls
confirms it):
  • Run containers with
    --network=host
    .
    Without it a container has no network at all — DNS fails (
    wget: bad address
    ). Image pulls still work either way, since dockerd itself sits on the sandbox's netstack.
  • Build with
    --network=host
    (compose:
    build: {context: ., network: host}
    ), or every
    RUN
    step dies with
    failed to solve: ... network bridge not found
    .
  • Container→container over
    127.0.0.1:<port>
    , never a compose service name — host networking means no bridge DNS, so
    db
    or
    api
    dies with
    gaierror: [Errno -2] Name or service not known
    . Plain
    localhost
    resolves fine; it is the service names that don't exist.
  • -p 8080:80
    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 (
    nginx
    configured for 8080,
    uvicorn --port 8080
    ); remapping it from the outside is not possible.
    docker run -p
    exits 0 and serves nothing.
  • A host-networked container listening on
    :8080
    is what the sandbox's public URL for 8080 serves — declare
    --port 8080
    /
    ports=[8080]
    at create, then
    sb.get_port_url(8080)
    .
Compose template that works as-is (FastAPI + Redis; run
docker compose up -d --build
detached with a generous timeout, since builds pull layers):
yaml
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: host
dockerd
以
--bridge=none --iptables=false --ip6tables=false
参数运行,因此仅存在
host
和
none
两种 Docker 网络(可通过
docker network ls
确认):
  • 运行容器时请使用
    --network=host
    。
    不加该参数的话容器完全没有网络——DNS 会失败(
    wget: bad address
    )。镜像拉取两种方式都可以,因为 dockerd 本身运行在沙箱的网络栈中。
  • 构建镜像时请使用
    --network=host
    (compose 中:
    build: {context: ., network: host}
    ),否则每个
    RUN
    步骤都会报错
    failed to solve: ... network bridge not found
    。
  • 容器之间通过
    127.0.0.1:<端口>
    通信
    ,不要使用 compose 服务名——主机网络模式下没有网桥 DNS,因此
    db
    或
    api
    这类名称会报错
    gaierror: [Errno -2] Name or service not known
    。普通的
    localhost
    可以正常解析;不存在的是服务名称。
  • -p 8080:80
    会被静默忽略
    ——端口发布属于网桥的功能,主机网络模式下没有网桥。容器已经在沙箱的网络栈中,因此容器内的进程必须监听你想要的端口(
    nginx
    配置为 8080、
    uvicorn --port 8080
    );无法从外部重新映射端口。
    docker run -p
    会以 0 退出,但不会提供任何服务。
  • 监听
    :8080
    的主机网络容器,其服务会通过沙箱的 8080 公共 URL 对外提供——创建时声明
    --port 8080
    /
    ports=[8080]
    ,然后调用
    sb.get_port_url(8080)
    即可。
可直接使用的 Compose 模板(FastAPI + Redis;请以分离模式运行
docker compose up -d --build
,并设置较长的超时时间,因为构建过程会拉取镜像层):
yaml
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: host

Docker gotchas

Docker 常见坑点

  • Where images live depends on the instance type — disk on
    cpu-1
    /
    cpu-4
    , RAM everywhere else — and it decides both your ceiling and whether
    storage_gb
    helps. 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.
  • A full data root fails the pull, it no longer kills the sandbox. Both backings return
    no space left on device
    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
    429 sandbox terminated: out of memory
    — if you see that, you overran the data root, so drop to a smaller image or move to
    cpu-1
    /
    cpu-4
    .
  • Restricted egress and image pulls don't mix. Under
    network_policy="deny-all"
    dockerd still starts, but every pull fails after a long stall with
    Get "https://registry-1.docker.io/v2/": context deadline exceeded
    . A CIDR allowlist doesn't rescue it: allowlisting the resolvers (
    1.1.1.1/32
    ,
    8.8.8.8/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.
  • Docker Engine is pinned to v27 (
    docker info
    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.
  • On a plain runtime,
    docker
    and
    dockerd
    are absent and
    mount
    returns
    permission denied
    , so you cannot add Docker after the fact — choose a
    -docker
    runtime at create time.
  • There is no
    docker
    field on the REST API. If you drive
    /v1/core/sandboxes
    directly, send
    "runtime": "node24-docker"
    .
  • 镜像存储位置取决于实例类型——
    cpu-1
    /
    cpu-4
    存在磁盘上,其他规格存在 RAM 中——这决定了你的空间上限以及
    storage_gb
    是否有用。参见镜像存储位置与可用空间;搞错这一点的话,你可能以为有 5 GB 预算,实际只有 4.4 GB 还要和进程共享内存。
  • 数据根目录满了只会导致拉取失败,不会再终止沙箱。 两种存储方式都会返回
    no space left on device
    ,且沙箱保持运行。如果你使用的是较旧的集群,可能仍会遇到旧行为:沙箱被终止,后续所有调用都返回
    429 sandbox terminated: out of memory
    ——如果看到这个错误,说明你超出了数据根目录的空间,请换用更小的镜像或迁移到
    cpu-1
    /
    cpu-4
    规格。
  • 受限出口策略和镜像拉取不能共存。 在
    network_policy="deny-all"
    下,dockerd 仍会启动,但每次拉取都会在长时间卡顿后报错
    Get "https://registry-1.docker.io/v2/": context deadline exceeded
    。CIDR 白名单也解决不了:将解析器(
    1.1.1.1/32
    、
    8.8.8.8/32
    ,参见下面的 DNS 坑点)加入白名单确实能修复域名解析,但拉取会卡在等待注册表 IP 上——而 Docker Hub 的 IP 由动态 CDN 提供,无法枚举。请将镜像打包到自定义镜像中,或者在默认开放出口的环境下拉取。
  • Docker Engine 固定为 v27(可通过
    docker info
    查看具体构建版本),v28+ 在此环境中已知有问题——不要在沙箱内升级,不支持该操作。Docker 仅支持 CPU 沙箱,不支持 GPU。
  • 在普通运行时中,
    docker
    和
    dockerd
    完全不存在,且
    mount
    命令会返回
    permission denied
    ,因此你无法事后添加 Docker——请在创建时选择
    -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 -y
Run 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
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 1800000
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
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 1800000

private 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 preinstalled

Raw 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=false
ORG_ID
from memberships:
lightning 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_ID
:
lightning api /v1/memberships | jq -r '[.memberships[] | select(.ownerType == "organization") | .ownerId][0]'
。

Gotchas

注意事项

  • Timeout units differ:
    create --timeout
    /
    extend_timeout()
    / snapshot
    --expiration
    are milliseconds;
    sandbox run --timeout
    (detached wait) is seconds.
  • Sandboxes keep billing until stopped/deleted and are not cleaned up by garbage collection — always
    stop()
    /
    delete()
    , and set a create-time
    timeout
    as a safety net.
  • sandbox delete
    and
    sandbox snapshot delete
    prompt for confirmation — pass
    -y
    /
    --yes
    non-interactively.
    Without it they read the prompt from a closed stdin, print
    Are you sure you want to delete? [y/N]: Aborted.
    and 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.
  • A CIDR allowlist does not implicitly permit DNS.
    allow_cidrs
    is enforced at the IP layer, and the sandbox's
    /etc/resolv.conf
    points at
    1.1.1.1
    and
    8.8.8.8
    — outside any realistic application allowlist — so every hostname lookup fails with
    Temporary failure in name resolution
    while raw-IP connections work. Include the resolver addresses (
    1.1.1.1/32
    ,
    8.8.8.8/32
    ) in the allowlist, or point the sandbox at a resolver inside it.
  • Files restored from a snapshot come back with mtime
    1970-01-01T00:00:00Z
    .
    Epoch-zero timestamps break
    make
    ,
    ccache
    , 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.
  • Egress policy is Python-SDK-only.
    sandbox create
    has no network-policy flag, so
    deny-all
    and CIDR allowlists require dropping into
    lightning_sdk
    ; everything else here (create, run, snapshot, list, delete) is CLI-doable.
  • There is no cost surface for sandboxes.
    /v1/billing/usage
    ,
    /v1/projects/<pid>/usage
    and
    /v1/core/sandboxes/<id>/usage
    all 404, no CLI reports spend, and sandbox instance types (
    cpu-1
    ,
    cpu-2
    ) don't appear in the priced accelerator catalog (or in
    lightning machine list
    ) — so a sandbox run cannot be priced, even by hand. Budget with a create-time
    timeout
    rather than by measuring after.
  • Ephemeral (default) sandboxes lose everything on stop; only
    persistent=True
    gives stop/resume. Snapshots capture the filesystem only, never running processes.
  • The default runtime is
    node24
    — Node.js only, no Python.
    Pass
    runtime="python313"
    /
    --runtime python313
    for Python workloads (naming:
    node22
    ,
    node24
    ,
    python313
    , plus the
    -docker
    variants; invalid ids fail with "invalid runtime").
    image
    (custom rootfs) is CPU/gVisor-only and mutually exclusive with
    runtime
    ; private images need
    image_secret_ref
    pointing at a Docker-registry secret.
  • To run containers inside a sandbox, use a
    -docker
    runtime (
    --runtime python313-docker
    ) or
    docker=True
    /
    --docker
    — never hand-install Docker on a plain runtime. See Docker inside a sandbox, especially the
    --network=host
    requirement.
  • Public port URLs only exist for ports declared at create time (
    ports=[8080]
    /
    --port 8080
    ); there is no way to expose a port later.
    create
    normally returns them already populated in
    port_urls
    ; if empty, re-
    get
    the sandbox.
  • Network policy is create-time only — you cannot change egress rules on a running sandbox. Default is open egress (
    allow-all
    ); use
    "deny-all"
    or CIDR allowlists for untrusted code.
  • Commands run as root inside the sandbox.
  • Scoped-key errors: the CLI and SDK turn the raw server errors into hints.
    Use a teamspace- or org-scoped API key ...
    (raw: "organization_id is required") → you're on a personal login key.
    Your teamspace-scoped API key is not authorized for the project requested via teamspace= ...
    (raw: "API key is not authorized for this project") → the key is bound to a different teamspace.
    This operation requires a teamspace-scoped API key ...
    → snapshot/stop with an org-scoped key. Only raw
    lightning api
    calls show the raw wording.
  • 超时时间单位不统一:
    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。
    allow_cidrs
    在 IP 层生效,而沙箱的
    /etc/resolv.conf
    指向
    1.1.1.1
    和
    8.8.8.8
    ——这些地址不在任何实际应用的白名单中——因此所有域名解析都会失败,报错
    Temporary failure in name resolution
    ,但直接 IP 连接可以正常工作。请将解析器地址(
    1.1.1.1/32
    、
    8.8.8.8/32
    )加入白名单,或者将沙箱指向内部的解析器。
  • 从快照恢复的文件的 mtime 为
    1970-01-01T00:00:00Z
    。
    零时间戳会破坏
    make
    、
    ccache
    以及 pip/setuptools 的新鲜度检查——这在快照最常用的预构建环境场景中影响最大。请 touch 你依赖的文件,或者在恢复的沙箱中避免使用基于 mtime 的新鲜度判断逻辑。
  • 出口策略仅 Python SDK 支持。
    sandbox create
    没有网络策略参数,因此
    deny-all
    和 CIDR 白名单需要使用
    lightning_sdk
    ;其他所有功能(创建、运行、快照、列表、删除)都可以通过 CLI 完成。
  • 沙箱没有费用查询接口。
    /v1/billing/usage
    、
    /v1/projects/<pid>/usage
    和
    /v1/core/sandboxes/<id>/usage
    都返回 404,没有 CLI 可以查询消费,且沙箱实例类型(
    cpu-1
    、
    cpu-2
    )不在定价的加速器目录中(也不在
    lightning machine list
    中)——因此即使手动计算也无法得出沙箱运行的费用。请通过创建时的
    timeout
    来控制预算,而不是事后统计。
  • 临时(默认)沙箱在停止后会丢失所有数据;只有
    persistent=True
    才支持停止/恢复。快照仅捕获文件系统,不包含运行中的进程。
  • 默认运行时是
    node24
    ——仅包含 Node.js,没有 Python。
    对于 Python 工作负载,请传入
    runtime="python313"
    /
    --runtime python313
    (命名规则:
    node22
    、
    node24
    、
    python313
    ,以及带
    -docker
    的变体;无效 ID 会报错 "invalid runtime")。
    image
    (自定义根文件系统)仅支持 CPU/gVisor,且与
    runtime
    互斥;私有镜像需要
    image_secret_ref
    指向 Docker 注册表密钥。
  • 要在沙箱内运行容器,请使用
    -docker
    运行时(
    --runtime python313-docker
    )或
    docker=True
    /
    --docker
    ——切勿在普通运行时上手动安装 Docker。参见沙箱内的 Docker,特别是
    --network=host
    的要求。
  • 公共端口 URL 仅对创建时声明的端口有效(
    ports=[8080]
    /
    --port 8080
    );无法后续暴露端口。
    create
    通常会返回已填充的
    port_urls
    ;如果为空,请重新
    get
    沙箱信息。
  • 网络策略仅创建时可设置——无法在运行中的沙箱上修改出口规则。默认是开放出口(
    allow-all
    );对于不可信代码,请使用
    "deny-all"
    或 CIDR 白名单。
  • 沙箱内的命令以 root 身份运行。
  • 范围密钥错误:CLI 和 SDK 会将原始服务器错误转换为提示。
    Use a teamspace- or org-scoped API key ...
    (原始错误:"organization_id is required")→ 你使用的是个人登录密钥。
    Your teamspace-scoped API key is not authorized for the project requested via teamspace= ...
    (原始错误:"API key is not authorized for this project")→ 该密钥绑定到了另一个 teamspace。
    This operation requires a teamspace-scoped API key ...
    → 使用组织范围密钥执行快照/停止操作。只有原始
    lightning api
    调用会显示原始错误信息。