SPAWNBOX

Guides

Run commands, build templates, use the coding agent templates, keep secrets outside the sandbox, control network access, fork, pause and more.

Type these commands on the host, or on your computer with the SSH tunnel from step 7. The examples use the variables A, B and S from step 6.

Run commands

# Get the result as JSON: stdout, stderr, exit_code and duration_ms
curl -s -H "$A" -d '{"cmd": "ls -la", "cwd": "/tmp"}' $B/sandboxes/$S/exec

# Send data to stdin
curl -s -H "$A" -d '{"cmd": "wc -l", "stdin": "a\nb\n"}' $B/sandboxes/$S/exec

# Get the output live, as server-sent events
curl -N -H "$A" -H "Accept: text/event-stream" \
  -d '{"cmd": "for i in 1 2 3; do echo $i; sleep 1; done"}' $B/sandboxes/$S/exec

# Start a background process that continues after the request ends
curl -s -H "$A" -d '{"cmd": "setsid python3 -m http.server 3000 >/dev/null 2>&1 &"}' \
  $B/sandboxes/$S/exec

Read and write files

curl -s -H "$A" -X PUT --data-binary @main.py "$B/sandboxes/$S/files?path=main.py"
curl -s -H "$A" "$B/sandboxes/$S/files?path=main.py"        # file contents
curl -s -H "$A" "$B/sandboxes/$S/files?path=/workspace"     # directory list as JSON
curl -s -H "$A" -X DELETE "$B/sandboxes/$S/files?path=old&recursive=true"

Make your own template

A template is a start image for sandboxes. Spawnbox runs the setup commands one time. Then it saves a snapshot. Sandboxes from your template start as fast as sandboxes from the base template.

  1. Create the template:

    curl -s -H "$A" $B/templates -d '{
      "name": "py",
      "setup": ["apt-get update && apt-get install -y build-essential", "pip install requests"],
      "env": {"PYTHONUNBUFFERED": "1"},
      "resources": {"vcpus": 2, "memory_mib": 2048, "disk_gib": 20}
    }'
  2. Get the template. Do this again until latest_build.state is ready:

    curl -s -H "$A" $B/templates/py
  3. Create a sandbox from the template:

    curl -s -H "$A" -d '{"template": "py"}' $B/sandboxes

NOTE: The base disk is Debian 13 with Node.js 26.13.1 (with npm) and Python 3.15.2 (with pip) in /usr/local. It has no apt package lists. Run apt-get update before you install packages.

Ready-made coding agent templates

The templates/ directory has template files for three coding agent CLIs. Each file installs one pinned npm package on the base disk:

File Package Command
templates/claude-code.json @anthropic-ai/[email protected] claude
templates/codex.json @openai/[email protected] codex
templates/copilot.json @github/[email protected] copilot

A first install starts a build of each template in the background. The builds take a few minutes, one time for each server. Builds stay after a restart. Then each sandbox starts from the saved snapshot, as fast as a sandbox from base:

spawnbox templates ls                   # wait until the build is ready
spawnbox create --template claude-code

The installer copies the files to /opt/spawnbox/templates. If you upgraded from an older version, or the install skipped the builds, build a template with the CLI:

spawnbox templates build /opt/spawnbox/templates/claude-code.json

Each template uses 2 vCPUs, 4096 MiB of memory and 20 GiB of disk. To get a newer agent, change the version in the file and build it again.

Give the agent its API key as a held secret, so the real key never enters the sandbox:

# Claude Code sends the key in the x-api-key header.
curl -s -H "$A" $B/secrets -d '{
  "name": "anthropic", "type": "http_header", "value": "sk-ant-...",
  "allowed_hosts": ["api.anthropic.com"], "env": "ANTHROPIC_API_KEY",
  "header": "x-api-key", "format": "{value}"
}'
curl -s -H "$A" -d '{"template": "claude-code", "secrets": ["anthropic"]}' $B/sandboxes

For Codex, use the openai secret from Use a secret safely (OPENAI_API_KEY).

NOTE: The held-secret setup for Copilot CLI is not documented here, because the hosts that it sends its token to are not verified.

Start a template from a container image

Set base to a container image. Spawnbox gets the image inside a builder VM, not on the host. Then it runs setup and saves a snapshot, as for other templates.

curl -s -H "$A" $B/templates -d '{
  "name": "node22",
  "base": "node:22-bookworm-slim",
  "setup": ["npm install -g pnpm"],
  "resources": {"disk_gib": 10}
}'
  • Use an image for linux/amd64. Use a digest, for example node@sha256:..., to always get the same image. Spawnbox reads a tag only when it builds the template.
  • The image environment variables (ENV) are set in each sandbox.
  • Spawnbox ignores the image ENTRYPOINT, CMD, USER and WORKDIR. Commands run as user (UID 1000) in /workspace. setup commands run as root.
  • The image must have /bin/sh. The unpacked image must fit in disk_gib.
  • The tenant’s network rules apply to the image download.
  • For a private registry, make a held secret for the registry host (for example an http_header secret with Authorization: Basic ...). Put its name in registry_secrets. Spawnbox adds it only while it gets the image. You can set a maximum of 4.

Use a devcontainer.json

The CLI changes an image-based devcontainer.json into a template:

spawnbox templates build .devcontainer/devcontainer.json --devcontainer --name web
  • image becomes base. containerEnv and remoteEnv become env.
  • onCreateCommand, updateContentCommand and postCreateCommand become setup commands. They run as root.
  • The CLI refuses build, dockerFile, dockerComposeFile and features. It refuses values with ${...}.
  • The CLI shows the other fields that it ignores, for example forwardPorts.

Keep builds in an object store

Spawnbox can save each template build in an S3-compatible object store, for example Amazon S3, Cloudflare R2, Garage or SeaweedFS. Then:

  • When you make a template again with the same settings, Spawnbox gets the build from the store. This is faster than a new build.
  • If the build files on the host are lost, Spawnbox gets them from the store.
  • You can set a limit for the disk that builds use on the host.
  1. Make a bucket in your object store, for example spawnbox-builds.

  2. On the host, open the settings file:

    sudo nano /etc/spawnbox/spawnbox.env
  3. Add --build-store s3://spawnbox-builds/builds to the SPAWNBOX_ARGS line.

  4. Add the access settings of your object store on new lines. Use your values:

    AWS_ENDPOINT=https://s3.example.com
    AWS_REGION=us-east-1
    AWS_ACCESS_KEY_ID=your-access-key
    AWS_SECRET_ACCESS_KEY=your-secret-key

    For Amazon S3, do not add AWS_ENDPOINT. For a store without HTTPS, also add AWS_ALLOW_HTTP=true.

  5. Optional: to limit the disk that builds use, add --build-cache-gib 50 to the SPAWNBOX_ARGS line.

  6. Save the file and restart the service:

    sudo systemctl restart spawnbox
  7. Make sure that the build store operates:

    sudo journalctl -u spawnbox -n 50 | grep "build store"

    After each new build, the log shows saved to the build store.

NOTE: With --build-cache-gib, Spawnbox removes builds from the host when the disk is more than the limit. It removes only builds that are in the store and that nobody used in the last 10 minutes. The next sandbox from such a template waits while Spawnbox gets the build (approximately 5 seconds for 1 GiB).

NOTE: With a build store, only one host builds a new template. That host writes a claim object under <prefix>/claims/. The other hosts log is being built on another host; waiting and get the build from the store when it is there. If the host that builds stops, the other hosts wait until its claim is 3 minutes old. Then one of them builds the template. The store must support create-only writes (If-None-Match: *). If it does not, the log shows a warning and each host builds the template.

NOTE: A worker that joins gets the templates with the most sandboxes in the last 7 days first. If its builds already use all of --build-cache-gib, it does not download more builds. It gets each one from the store when a sandbox first uses it.

NOTE: On a Firecracker host, the first sandbox from a build that is only in the store does not wait for all of the memory. Spawnbox gets the disks, starts the sandbox, and gets the memory while it runs. The parts that the sandbox asks for come first. If a part is not available for 30 seconds, Spawnbox stops the sandbox. Its state becomes failed, and it gets a sandbox.lost event. A pause or a fork of such a sandbox waits until its memory is on the host.

NOTE: If a sandbox’s VM stops on its own, for example because the guest crashed, Spawnbox notices within a second. The sandbox’s state becomes failed, it gets a sandbox.lost event, and calls to it return 409 conflict. A warm VM that stopped is replaced by a normal start.

NOTE: Spawnbox deletes objects in the store that no host used for 7 days. Do not keep other data under the same prefix.

Open a terminal

Install websocat. Then type:

websocat -H "$A" --binary "ws://127.0.0.1:8080/v1/sandboxes/$S/pty?cols=120&rows=40"

Type exit to close the terminal.

Open a terminal or a private preview in a browser

Do not give your API key to a browser. Get a session token for one sandbox from your server, and give the token to the browser. A token opens one thing: the terminal, or the private preview of one port.

curl -s -H "$A" -d '{"ttl_s": 900, "audience": "terminal"}' $B/sandboxes/$S/session-tokens
curl -s -H "$A" -d '{"ttl_s": 900, "audience": "preview", "port": 3000}' \
  $B/sandboxes/$S/session-tokens
  • For the terminal, the browser opens ws://127.0.0.1:8080/v1/sandboxes/$S/pty?session_token=<token>.
  • For a private preview URL, add ?spawnbox_session=<token> to the URL. At the first visit, the token becomes a cookie.

The token stops after ttl_s seconds (maximum 900). It also stops when you revoke the API key that made it.

Clone a repository

curl -s -H "$A" -d '{"url": "https://github.com/octocat/Hello-World", "depth": 1}' \
  $B/sandboxes/$S/git:clone

Show a web app with a preview URL

  1. Start a web server in the sandbox. The server can listen on 127.0.0.1.

  2. Publish its port:

    curl -s -H "$A" -d '{"port": 3000}' $B/sandboxes/$S/ports
  3. Open the url from the output in your browser.

Keep a program running with a service

A service is a program that Spawnbox keeps running in the sandbox. Give the services when you create the sandbox:

curl -s -H "$A" $B/sandboxes -d '{
  "services": [{
    "name": "web",
    "command": ["python3", "-m", "http.server", "8000"],
    "cwd": "/workspace",
    "env": {"LOG_LEVEL": "info"},
    "port": 8000,
    "access": "private",
    "health": {"http": "/", "interval_s": 10, "failures": 3},
    "restart": "always"
  }]
}'
  • Spawnbox starts each service as user, with the env of the sandbox and then the env of the service.
  • If a service stops, Spawnbox starts it again. It waits 1 s, then 2 s, 4 s and up to 30 s. After 60 s of good operation, the wait is 1 s again. With "restart": "on-failure", a service that exits with code 0 stays stopped.
  • A health check is {"http": "/path"} (a GET must give a 2xx status) or {"tcp": true} (the port must accept a connection). If the check fails failures times one after the other, Spawnbox restarts the service.
  • Spawnbox publishes the port of a service with its access (default private). A preview request waits up to 30 s for the service to be healthy.
  • The last 1 MiB of output of each service is in /var/log/spawnbox/<name>.log in the sandbox.
  • A pause keeps the services and their processes. A resume does not restart them. A cold start of a persistent sandbox starts them again.
  • Sandboxes from a template made before services were added cannot have services. The create gives 409 conflict. Build the template again.

Pause and resume a sandbox

curl -s -H "$A" -X POST $B/sandboxes/$S:pause    # releases CPU and memory
curl -s -H "$A" -X POST $B/sandboxes/$S:resume   # processes continue

Usually, you do not need these commands. A sandbox pauses automatically after 10 minutes without requests. The next exec, file, terminal, clone or preview request resumes it.

Keep a sandbox until you delete it

S=$(curl -s -H "$A" -d '{"persistent": true}' $B/sandboxes | jq -r .id)

A persistent sandbox has no timeout. It pauses after 10 minutes without requests and stays paused until the next request. Paused retention does not delete it.

If Spawnbox cannot keep its memory, the sandbox becomes cold. This occurs when the server crashes, the VM stops on its own, a pause or a resume fails, the snapshot_storage_gib quota has no room for its idle pause, or the server stops before the sandbox can pause. The sandbox.cold event has the reason. The next exec, file, terminal, clone, preview or resume request starts it again from its template build. The processes and the files outside its volumes are gone. Its ID, env, secrets, network rules, volumes and published ports are the same.

A tenant needs the persistent_sandboxes quota. It is 0 by default. The primary admits each persistent sandbox and keeps its quota and its start record. By default it also runs the first VM. With --persistent-placement any on the primary, the first VM starts on a worker that ranks above the primary and has a build of the template’s current spec. Only workers of this version or later take a first start. The primary never builds a template on a worker for this. If no worker can start it for sure, the primary starts it. If the primary cannot know whether the worker started it, the create gives 503 node_unreachable with the sandbox ID in the message. The sandbox is kept: it is cold, or it runs on the worker, and the next call to it starts it or reaches it. :migrate cannot copy a persistent sandbox to another host with its memory (409). In a fleet, a cold sandbox can start again on any worker that has its template build. Refer to Fence lost hosts. To run one on another host, let it become cold: it then starts on the host that takes the next call, from a build of that host. A drain does this for you.

Upgrades and old builds

The guest in a sandbox is part of its template build. A host accepts guests up to two minor versions older or newer than its own. A persistent sandbox can live longer than that, and the host that starts it can lack its build, for example after a leader failover. So:

  • A paused persistent sandbox whose guest the host no longer accepts is not resumed. It becomes cold with the reason guest_too_old, and the call starts it again from its start record.
  • A cold start uses the recorded build if this host has it, or can get it from the build store, and accepts its guest. If not, it uses a ready build of this host made from the same template spec, or builds that spec again with the current guest, as a template rebuild does. The sandbox then starts from that build from now on, and the event sandbox.rebuilt shows from_build, to_build and the reason: missing (no host file and not in the store), outdated (made with another kernel, base disk, runtime or disk IO engine) or guest_too_old.
  • Cold starts on one host that need the same spec wait for one build. On the primary, the call waits up to 60 seconds for it. When the sandbox starts on a worker, the call does not wait. In both cases, the call gives 503 rebuilding while the build goes on; try again.
  • If the spec cannot be built, the call gives 409 build_failed with the error, and the sandbox stays cold. The same error is given for the next 5 minutes, then the next call builds again. If a worker cannot build the spec, the primary starts the sandbox itself, and does not ask that worker to build the spec again for 5 minutes. A sandbox from a snapshot template cannot be built again on another host or version.
  • When a paused sandbox on a worker becomes cold this way, the worker tells the primary at once, and the primary starts the sandbox again for the same call. If that takes too long, the call gives 503 sandbox_cold; try again.

Fork a sandbox or save it as a template

curl -s -H "$A" -d '{"count": 3}' $B/sandboxes/$S:fork
curl -s -H "$A" -d '{"name": "with-deps"}' $B/sandboxes/$S:snapshot
curl -s -H "$A" -d '{"template": "with-deps"}' $B/sandboxes

Each copy starts with the files and the running processes of $S. $S continues to run. Use a fork to try different changes from the same point. Use a snapshot when you will need the same state again later.

Keep files in a volume

The files of a sandbox go away when you delete the sandbox. To keep files, put them in a volume. A volume is a disk with a name. It stays until you delete it.

  1. Create a volume of 5 GiB:

    curl -s -H "$A" $B/volumes -d '{"name": "work", "size_gib": 5}'
  2. Create a sandbox that mounts the volume at /data, and write a file:

    S=$(curl -s -H "$A" $B/sandboxes -d '{
      "volumes": [{"volume": "work", "path": "/data"}]
    }' | jq -r .id)
    curl -s -H "$A" $B/sandboxes/$S/exec -d '{"cmd": "echo hello > /data/note"}'
  3. Delete the sandbox. Then create a new sandbox with the same volume. The file /data/note is there.

Rules:

  • One sandbox can write to a volume at a time.
  • Many sandboxes can mount a volume with "read_only": true at the same time. They cannot do this while a sandbox writes to the volume.
  • If a volume is in use, the response is 409.
  • A sandbox can mount 1 to 4 volumes.
  • The user user owns the files on a new volume.
  • A volume keeps its data when the sandbox pauses, resumes or moves to a different host.
  • A volume works only with the backend of the first sandbox that mounted it: Firecracker or gVisor.

CAUTION: A volume is on the disk of one host. Spawnbox does not make a backup copy. If you lose the host, you lose the volume.

Control network access

This sandbox can connect only to github.com and to subdomains of pypi.org:

curl -s -H "$A" $B/sandboxes -d '{
  "egress": {"mode": "allowlist", "allow": ["github.com", "*.pypi.org"]}
}'

Use a secret safely

  1. Save the secret:

    curl -s -H "$A" $B/secrets -d '{
      "name": "openai", "type": "http_header", "value": "sk-...",
      "allowed_hosts": ["api.openai.com"], "env": "OPENAI_API_KEY"
    }'
  2. Create a sandbox with the secret:

    curl -s -H "$A" -d '{"secrets": ["openai"]}' $B/sandboxes

In the sandbox, $OPENAI_API_KEY contains a placeholder, for example sbx_ph_.... When code sends an HTTPS request to api.openai.com, Spawnbox puts the real key in the request. Other hosts get only the placeholder.

Serve many customers

Use your org key to create a tenant and a key for that tenant. The tenant key can see only the sandboxes of its tenant.

curl -s -H "$A" $B/tenants -d '{"id": "acme", "name": "Acme",
  "quotas": {"running_sandboxes": 5, "monthly_egress_bytes": 10000000000}}'
curl -s -H "$A" $B/keys -d '{"tenant": "acme", "name": "acme-prod"}'

Firecracker or gVisor

Spawnbox has two backends. A backend is the technology that isolates a sandbox. Each host uses one backend for all its sandboxes.

Item Firecracker gVisor
Host Needs KVM Does not need KVM. A usual cloud VM is sufficient.
Isolation Each sandbox is a microVM with its own Linux kernel. The CPU hardware isolates it. Each sandbox has the gVisor kernel. This kernel is a program on the host that does the system calls of the sandbox. This isolation is less strong than a microVM.
Linux functions All Most. Some programs that use special kernel functions do not operate, for example programs that load kernel modules.
API and functions All All. Pause, resume, warm pools and moves between hosts operate the same.

Spawnbox selects the backend when it starts:

  • If Spawnbox can open /dev/kvm, it uses Firecracker.
  • If it cannot open /dev/kvm, it uses gVisor.

To select a backend yourself, add --backend firecracker or --backend gvisor to the settings. Refer to Configuration.

To see the backend of a host, type this command on the host:

sudo journalctl -u spawnbox | grep "sandboxes run in"

Some customers must have microVM isolation. Set isolation of their tenant to microvm-only:

curl -s -H "$A" -X PATCH $B/tenants/acme -d '{"isolation": "microvm-only"}'

Then Spawnbox puts the sandboxes of this tenant only on Firecracker hosts. If no Firecracker host has space, a create gives 503 no_capacity. The default value of isolation is any.

See events and usage

# Tag a request with the step ID of your agent, then find its events
curl -s -H "$A" -H "X-Spawnbox-Step: tool-call-42" -d '{"cmd": "make"}' $B/sandboxes/$S/exec
curl -s -H "$A" "$B/events?step_id=tool-call-42"

# Stream all new events
curl -N -H "$A" "$B/events?follow=true"

# Get the usage for this month, for each sandbox
curl -s -H "$A" "$B/usage?group_by=sandbox"

See metrics in Prometheus

Start the server with --metrics-listen 127.0.0.1:9464. Then each host shows Prometheus metrics at http://127.0.0.1:9464/metrics. This address has no authentication. Use only a private address.

curl -s http://127.0.0.1:9464/metrics | grep spawnbox_create_seconds_count

Each metric is about the host that shows it. On a fleet, scrape each host. Prometheus adds the instance label.

Metric Labels Meaning
spawnbox_create_seconds (histogram) path (warm, cached, cold), backend Time to create a sandbox. cold means that the host got the build from the build store first.
spawnbox_create_step_seconds (histogram) step (prepare, restore, fixups), backend Time of each step of a create
spawnbox_api_errors_total code Error responses
spawnbox_egress_connections_total verdict Connections from sandboxes and template builds
spawnbox_dns_queries_total verdict DNS queries from sandboxes and template builds
spawnbox_sandboxes (gauge) state Sandboxes on the host that are starting, running, paused or cold
spawnbox_node_committed_ratio (gauge) resource (slots, memory) Part of the host in use, from 0 to 1
spawnbox_warm_pool_ready (gauge) template, build, network Warm VMs ready
spawnbox_warm_pool_hits_total, spawnbox_warm_pool_misses_total build Creates that got or did not get a warm VM
spawnbox_fleet_nodes (gauge) state Primary only: workers in each state
spawnbox_fleet_load (gauge) None Primary only: load of the primary and the ready workers that are not drained, from 0 to 1
spawnbox_service_restarts_total (counter) reason Restarts of services
spawnbox_fleet_create_refused_total (counter) reason Primary only: creates refused with no_capacity
spawnbox_self_fences_total (counter) reason (self_fenced, lease_lost) Times this host stopped its persistent sandboxes because it lost the primary or its lease
spawnbox_fenced_cold_total (counter) reason Primary only: persistent sandboxes of a lost host that became cold, by proof (operator, autoscaler, self_fence, failover)
spawnbox_stale_copies_total (counter) None Copies of persistent sandboxes from an older generation that a host deleted
spawnbox_sandbox_rebuilds_total (counter) reason (missing, outdated, guest_too_old) Cold starts of persistent sandboxes that used a new build of their template spec, because the recorded build could not be used
spawnbox_fleet_retirements (gauge) state Primary only: workers that retire, in each state (draining, blocked, ready_to_terminate)
spawnbox_creates_total (counter) result (ok or an error code) Create calls, by result
spawnbox_cold_starts_total (counter) result (ok or an error code) Cold starts of persistent sandboxes on this host, by result
spawnbox_cold_start_seconds (histogram) None Time of each cold start that worked
spawnbox_leader_term (gauge) holder (this host’s ID) The term of the database lease this server holds as the primary. Only the leader shows it. It goes up each time a primary takes the lease: at a failover, and when the same primary restarts. A new holder means another host took over.
spawnbox_data_dir_available_bytes, spawnbox_data_dir_size_bytes (gauges) None Free space and size of the file system of --data-dir
spawnbox_start_time_seconds (gauge) None When this server process started, in seconds since the Unix epoch. It changes at each restart.
spawnbox_forward_requests_total (counter) code (ok or an error code) Requests on the forward listener, by result
spawnbox_forward_wakes_total (counter) None Sandboxes that the forward listener woke
spawnbox_forward_wake_wait_seconds (histogram) None Time that forwarded requests waited for a wake

deploy/prometheus/spawnbox-alerts.yml has alert rules for these metrics. Each alert is described, with its likely cause and first response, in deploy/prometheus/README.md.

This page is the “How to use Spawnbox” section of README.md ↗. Found a mistake? Edit it on GitHub ↗