### Install and start your own unit (nginx)
Source: https://docs.microsandbox.dev/examples/guest/systemd-services
Install nginx and start it with systemctl enable --now. Note that packages with policy-rc.d deferral install but don't auto-start; systemctl enable --now starts them in one step.
```bash
root@msb:/# apt update && apt install -y nginx
root@msb:/# systemctl enable --now nginx
root@msb:/# curl -s localhost | head -1
```
--------------------------------
### Create and Run a Sandbox in Go
Source: https://docs.microsandbox.dev/sdk/overview
Example of ensuring the runtime is installed, creating a sandbox, and executing a command.
```go
package main
import (
"context"
"fmt"
"log"
m "github.com/superradcompany/microsandbox/sdk/go"
)
func main() {
ctx := context.Background()
if err := m.EnsureInstalled(ctx); err != nil {
log.Fatal(err)
}
sb, err := m.CreateSandbox(ctx, "hello", m.WithImage("python"))
if err != nil {
log.Fatal(err)
}
defer func() {
_ = sb.Stop(context.Background())
_ = sb.Close()
}()
out, err := sb.Exec(ctx, "python", []string{"-c", "print('Hello, World!')"})
if err != nil {
log.Fatal(err)
}
fmt.Println("Output:", out.Stdout())
}
```
--------------------------------
### Install microsandbox SDK (Go)
Source: https://docs.microsandbox.dev/getting-started/quickstart
Install the Go SDK via go get.
```bash
go get github.com/superradcompany/microsandbox/sdk/go
```
--------------------------------
### Sandbox.start() example
Source: https://docs.microsandbox.dev/sdk/python/sandbox
Example usage of start() to restart a previously stopped sandbox named 'api'.
```python
sb = await Sandbox.start("api")
```
--------------------------------
### Create the startup script
Source: https://docs.microsandbox.dev/examples/development/vnc-desktop
Host-side shell script to install a desktop, start TigerVNC, launch LXQt, and serve noVNC.
```sh
#!/bin/sh
set -eu
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
breeze-icon-theme ca-certificates dbus-x11 lxqt-core novnc openbox \
qterminal tigervnc-standalone-server websockify
rm -rf /var/lib/apt/lists/*
mkdir -p /root/.config/lxqt /root/.config/openbox /tmp/runtime-root
chmod 700 /tmp/runtime-root
sed -e "s/,quicklaunch//" -e "/^[quicklaunch]/,/^$/d" \
/usr/share/lxqt/panel.conf > /root/.config/lxqt/panel.conf
sed "s#Clearlooks#Breeze-ob#" \
/etc/xdg/openbox/rc.xml > /root/.config/openbox/rc.xml
Xtigervnc :1 -SecurityTypes None -geometry 1440x900 -depth 24 >/tmp/xvnc.log 2>&1 &
vnc_pid=$!
sleep 2
if ! kill -0 "$vnc_pid"; then
cat /tmp/xvnc.log >&2
exit 1
fi
cat /tmp/xvnc.log
DISPLAY=:1 XDG_RUNTIME_DIR=/tmp/runtime-root \
dbus-launch --exit-with-session sh -c "
startlxqt &
session_pid=\$!
sleep 4
kill -0 \"\$session_pid\"
qterminal &
wait \"\$session_pid\"
" >/tmp/lxqt.log 2>&1 &
desktop_pid=$!
sleep 5
if ! kill -0 "$desktop_pid"; then
cat /tmp/lxqt.log >&2
exit 1
fi
exec websockify --web=/usr/share/novnc 0.0.0.0:6080 localhost:5901
```
--------------------------------
### Example: create a snapshot with SandboxHandle.snapshot()
Source: https://docs.microsandbox.dev/sdk/python/snapshots
Example showing how to get a sandbox handle and create a snapshot named 'after-pip-install'. The snapshot digest is printed.
```python
handle = await Sandbox.get("baseline")
snap = await handle.snapshot("after-pip-install")
print(snap.digest)
```
--------------------------------
### Create and Run a Sandbox in Ruby
Source: https://docs.microsandbox.dev/sdk/overview
Example of installing the runtime and using a block to manage the sandbox lifecycle.
```ruby
require "microsandbox"
Microsandbox.install unless Microsandbox.installed?
Microsandbox::Sandbox.with("hello", image: "python") do |sandbox|
output = sandbox.exec("python", ["-c", "print('Hello, World!')"])
puts "Output: #{output.stdout}"
end
```
--------------------------------
### Verify Pi installation
Source: https://docs.microsandbox.dev/examples/agents/pi
Exit Pi and run this to verify the installation. The pinned example prints 0.73.1.
```sh
msb exec pi-demo -- pi --version
```
--------------------------------
### Start OpenCode with msb run (macOS/Linux)
Source: https://docs.microsandbox.dev/examples/agents/opencode
Runs OpenCode in a microVM with a writable host-directory mount. Replace ./my-project with your project directory. The first run downloads the package and may take a couple of minutes. OpenCode should render its prompt and offer /connect for provider setup.
```sh
msb run -t --name opencode-demo --replace \
--cpus 2 --memory 2G --root-disk 4G \
--mount-dir ./my-project:/workspace:rw \
--workdir /workspace \
node:24-bookworm-slim -- sh -lc '
apt-get update &&
apt-get install -y --no-install-recommends ca-certificates git &&
npm install -g opencode-ai@1.18.4 &&
exec opencode
'
```
--------------------------------
### TypeScript custom installation
Source: https://docs.microsandbox.dev/sdk/setup
Uses the setup builder to configure the base directory, version, verification, and force download settings.
```typescript
import { setup } from "microsandbox";
await setup()
.baseDir("/opt/microsandbox")
.version("0.6.8")
.skipVerify(false)
.force(true)
.install();
```
--------------------------------
### Start Pi with msb run (macOS & Linux)
Source: https://docs.microsandbox.dev/examples/agents/pi
Runs a sandbox with a writable host-directory mount and installs the pinned Pi package version. Configure a provider from the TUI when prompted. Local-only: on microsandbox cloud, use the isolated-copy alternative and omit replace-on-create.
```sh
msb run -t --name pi-demo --replace \
--cpus 2 --memory 2G --root-disk 4G \
--mount-dir ./my-project:/workspace:rw \
--workdir /workspace \
node:24-bookworm-slim -- sh -lc '
apt-get update &&
apt-get install -y --no-install-recommends ca-certificates git &&
npm install -g @mariozechner/pi-coding-agent@0.73.1 &&
exec pi
'
```
--------------------------------
### Start method
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Boots a stopped sandbox and attaches the returned local handle.
```go
Start(ctx)
```
--------------------------------
### prepare_server usage example
Source: https://docs.microsandbox.dev/sdk/python/ssh
An example showing how to initialize the SSH server with specific authorized keys and user settings, followed by serving the connection.
```python
server = await sb.ssh().prepare_server(
authorized_keys_path="/home/me/.ssh/authorized_keys",
user="app",
sftp=False,
)
await server.serve_connection()
```
--------------------------------
### Install and verify runtime in Rust
Source: https://docs.microsandbox.dev/sdk/setup
Checks for the runtime installation and performs an installation if missing using the setup module.
```rust
use microsandbox::setup;
if !setup::is_installed() {
setup::install().await?;
}
```
--------------------------------
### MetricsStream usage example
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Example of starting a metrics subscription and processing the stream in a loop.
```go
stream, err := sb.MetricsStream(ctx, 500*time.Millisecond)
if err != nil {
return err
}
defer stream.Close()
for {
metrics, err := stream.Recv(ctx)
if err != nil || metrics == nil {
break
}
fmt.Printf("CPU: %.1f%%\n", metrics.CPUPercent)
}
```
--------------------------------
### Prepare an SSH server example
Source: https://docs.microsandbox.dev/sdk/go/ssh
Example of preparing an SSH server with a custom authorized keys path.
```go
srv, err := sb.SSH().PrepareServer(ctx,
m.WithSSHAuthorizedKeysPath("/etc/msb/authorized_keys"),
)
if err != nil {
return err
}
defer srv.Close(ctx)
```
--------------------------------
### Sandbox.get() example
Source: https://docs.microsandbox.dev/sdk/typescript/sandbox
Example of getting a handle to a sandbox named 'api' and logging its status.
```typescript
const handle = await Sandbox.get("api");
console.log(handle.status);
```
--------------------------------
### ConnectOrStart method
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Connects to a running sandbox, waits for it to start, or starts it if it is created, stopped, or crashed. Draining and paused states are rejected.
```go
func (h *SandboxHandle) ConnectOrStart(ctx context.Context, opts ...ConnectOrStartOption) (*Sandbox, error)
```
--------------------------------
### Sandbox::get() example
Source: https://docs.microsandbox.dev/sdk/rust/sandbox
Example of getting a handle to the sandbox named 'api' and printing its status.
```rust
let handle = Sandbox::get("api").await?;
println!("{:?}", handle.status());
```
--------------------------------
### Modify Sandbox Configuration Examples
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Examples demonstrating live resizing, dry-run previews, environment changes, disk resizing, and secret management.
```go
// Live resize: applies to the running VM when within the booted capacity
plan, err := sb.Modify(ctx, m.ModifyOptions{CPUs: 4, MemoryMiB: 4096})
if err != nil {
return err
}
for _, r := range plan.ResizeStatus {
fmt.Printf("%s: %s -> %s (%s)\n", r.Resource, r.Requested, r.Actual, r.State)
}
// Preview a change without applying it
preview, err := sb.Modify(ctx, m.ModifyOptions{MaxMemoryMiB: 16384, DryRun: true})
if err != nil {
return err
}
for _, c := range preview.Changes {
fmt.Printf("%s: %s\n", c.Field, c.Disposition)
}
// Make an env change active now by restarting
_, err = sb.Modify(ctx, m.ModifyOptions{
Env: map[string]string{"MODE": "prod"},
Policy: m.ModificationPolicyRestart,
})
// Grow the managed OCI root disk offline and restart
_, err = sb.Modify(ctx, m.ModifyOptions{
RootDiskSizeMiB: 8192,
Policy: m.ModificationPolicyRestart,
})
// Add or rotate a host-environment secret; restart if it is newly added
_, err = sb.Modify(ctx, m.ModifyOptions{
Secrets: map[string]m.SecretModifySpec{
"API_KEY": {
Env: "API_KEY",
AllowedHosts: []string{"api.example.com"},
},
},
Policy: m.ModificationPolicyRestart,
})
// Remove an existing secret
_, err = sb.Modify(ctx, m.ModifyOptions{
SecretsRemove: []string{"OLD_API_KEY"},
})
```
--------------------------------
### Verify Codex installation
Source: https://docs.microsandbox.dev/examples/agents/codex
Checks the installed Codex version. The pinned example prints codex-cli 0.148.0.
```sh
msb exec codex-demo -- codex --version
```
--------------------------------
### Booting from disk images in Go
Source: https://docs.microsandbox.dev/images/overview
Illustrates how to use Go options to boot from disk images with auto-detection or explicit filesystem types.
```go
// Auto-detect format from the file extension
sb, err := m.CreateSandbox(ctx, "custom-vm",
m.WithImage("./ubuntu-22.04.qcow2"),
m.WithCPUs(2),
m.WithMemory(2048),
)
// Explicit filesystem type
sb2, err := m.CreateSandbox(ctx, "custom-vm-2",
m.WithImageDisk("./alpine.raw", "ext4"),
m.WithCPUs(1),
m.WithMemory(512),
)
```
--------------------------------
### Verify Gemini CLI installation
Source: https://docs.microsandbox.dev/examples/agents/gemini-cli
Verifies the installed Gemini CLI version. The pinned example prints 0.52.0.
```sh
msb exec gemini-demo -- gemini --version
```
--------------------------------
### Retrieve Sandbox Metrics Example
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Example showing how to fetch and print current CPU and memory usage.
```go
metrics, err := sb.Metrics(ctx)
fmt.Printf("cpu %.1f%% ยท mem %d MiB\n",
metrics.CPUPercent, metrics.MemoryBytes/(1<<20))
```
--------------------------------
### Boot sandbox from snapshot or image
Source: https://docs.microsandbox.dev/sdk/python/snapshots
Example showing two ways to create a sandbox: booting from a snapshot artifact using from_snapshot, or from an image using image. Only one of the two can be passed.
```python
# Boot from a snapshot
sb = await Sandbox.create("worker", from_snapshot="after-pip-install")
# Or from an image (existing flow, unchanged)
sb = await Sandbox.create("worker", image="python:3.12")
```
--------------------------------
### Image.Inspect() example
Source: https://docs.microsandbox.dev/sdk/go/images
Example usage of Image.Inspect to get detailed information about a cached image and print its entrypoint and layer count.
```go
detail, err := m.Image.Inspect(ctx, "python:3.12")
if err != nil {
return err
}
fmt.Println(detail.Config.Entrypoint, len(detail.Layers), "layers")
```
--------------------------------
### Verify OpenCode installation
Source: https://docs.microsandbox.dev/examples/agents/opencode
Exits the TUI and runs opencode --version to verify the installation. The pinned example prints 1.18.4.
```sh
msb exec opencode-demo -- opencode --version
```
--------------------------------
### ServeConnection usage example
Source: https://docs.microsandbox.dev/sdk/go/ssh
Example showing how to prepare an SSH server and serve a connection.
```go
srv, err := sb.SSH().PrepareServer(ctx)
if err != nil {
return err
}
defer srv.Close(ctx)
if err := srv.ServeConnection(ctx); err != nil {
return err
}
```
--------------------------------
### Verify Claude Code installation
Source: https://docs.microsandbox.dev/examples/agents/claude-code
Checks the installed Claude Code version. The pinned example prints `2.1.235 (Claude Code)`.
```sh
msb exec claude-code-demo -- claude --version
```
--------------------------------
### Example: prepareServer() and serveConnection()
Source: https://docs.microsandbox.dev/sdk/typescript/ssh
Example usage of prepareServer() with a user option, followed by serving a connection.
```typescript
const server = await sandbox.ssh().prepareServer({ user: "root" });
await server.serveConnection();
```
--------------------------------
### fs.Mkdir() example
Source: https://docs.microsandbox.dev/sdk/go/filesystem
Creates a directory and any missing parent directories.
```go
err := fs.Mkdir(ctx, "/app/cache/sessions")
```
--------------------------------
### Verify installed OpenClaw version
Source: https://docs.microsandbox.dev/examples/agents/openclaw
Checks the installed OpenClaw version in the setup sandbox. The pinned package reports 'OpenClaw 2026.7.1-2'.
```sh
msb exec openclaw-setup -- openclaw --version
```
--------------------------------
### Minimal example in Go
Source: https://docs.microsandbox.dev/getting-started/introduction
Create a sandbox with the Python image, execute a Python command, print stdout, and stop the sandbox.
```go
sb, err := m.CreateSandbox(ctx, "hello", m.WithImage("python"))
if err != nil {
return err
}
defer sb.Stop(ctx)
out, err := sb.Exec(ctx, "python", []string{"-c", "print('Hello from a microVM!')"})
if err != nil {
return err
}
fmt.Println(out.Stdout())
```
--------------------------------
### SnapshotHandle usage example
Source: https://docs.microsandbox.dev/sdk/typescript/snapshots
Example showing how to get a live handle, open it, and remove it with force set to false. The remove call will refuse if the snapshot has children.
```typescript
const h = await Snapshot.get("after-pip-install");
const snap = await h.open(); // metadata-validated
await h.remove({ force: false }); // refuse if it has children
```
--------------------------------
### Create Sandbox with Image.disk()
Source: https://docs.microsandbox.dev/sdk/python/images
Example showing how to initialize a Sandbox using a disk image as the root filesystem.
```python
sb = await Sandbox.create(
"api",
image=Image.disk("/data/root.qcow2", fstype="ext4"),
)
```
--------------------------------
### Run microsandbox doctor
Source: https://docs.microsandbox.dev/troubleshooting/linux
Start with the doctor command for local setup checks.
```bash
msb doctor
```
--------------------------------
### readyBytes() example: decoding cached ready frame
Source: https://docs.microsandbox.dev/sdk/typescript/agent-client
Example of using readyBytes() to get the cached handshake core.ready frame body and decode it with cbor-x. This is a synchronous accessor with no protocol traffic.
```typescript
import { decode } from "cbor-x";
const ready = decode(client.readyBytes());
```
--------------------------------
### fs.stat_with_follow() signature and example
Source: https://docs.microsandbox.dev/sdk/rust/filesystem
Gets metadata, choosing whether to follow a final symlink. With follow_symlink = false you stat the link itself rather than its target. The example stats /app/current without following.
```rust
async fn stat_with_follow(&self, path: &str, follow_symlink: bool) -> MicrosandboxResult
```
```rust
let link_meta = sb.fs().stat_with_follow("/app/current", false).await?;
println!("{:?}", link_meta.kind);
```
--------------------------------
### Install CLI on Linux and macOS
Source: https://docs.microsandbox.dev/cli/overview
Use the install script to set up the runtime in ~/.microsandbox/ and create command links in ~/.local/bin/.
```bash
curl -fsSL https://install.microsandbox.dev | sh
```
--------------------------------
### fs.stat() signature and example
Source: https://docs.microsandbox.dev/sdk/rust/filesystem
Gets metadata for a file or directory: kind, size, mode, read-only flag, and timestamps. Follows a final symlink by default. The example prints size and mode.
```rust
async fn stat(&self, path: &str) -> MicrosandboxResult
```
```rust
let meta = sb.fs().stat("/app/config.json").await?;
println!("{} bytes, mode {:o}", meta.size, meta.mode);
```
--------------------------------
### handle.connectOrStart(options?)
Source: https://docs.microsandbox.dev/sdk/typescript/sandbox
Connects to an existing sandbox or starts a stopped or crashed sandbox. Optional options may be provided.
```APIDOC
## handle.connectOrStart(options?)
### Description
Connects to an existing sandbox or starts a stopped or crashed sandbox. Optional options may be provided.
### Method
connectOrStart
### Endpoint
handle.connectOrStart(options?)
### Parameters
- **options** (object) - Optional - Options for connecting or starting.
### Returns
- **Promise** - A promise that resolves to a Sandbox instance.
```
--------------------------------
### RootDisk Configuration Examples
Source: https://docs.microsandbox.dev/sdk/python/images
Demonstrates how to create managed, temporary, and existing root disk configurations using the RootDisk factory.
```python
from microsandbox import DiskImageFormat, RootDisk
managed = RootDisk.managed(8192)
temporary = RootDisk.tmpfs(512)
existing = RootDisk.disk(
"/data/upper.raw",
format=DiskImageFormat.RAW,
fstype="ext4",
)
```
--------------------------------
### Init.Cmd() usage example
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Example of using Init.Cmd() to specify an absolute path for the init binary along with arguments and environment variables.
```go
m.WithInit(m.Init.Cmd(
"/lib/systemd/systemd",
m.InitOptions{
Args: []string{"--unit=multi-user.target"},
Env: map[string]string{"container": "microsandbox"},
},
))
```
--------------------------------
### GetDefaultVolume usage example
Source: https://docs.microsandbox.dev/sdk/go/volumes
Shows how to get the default volume and use its FS() to write and read a file.
```go
volume, err := m.GetDefaultVolume(ctx)
err = volume.FS().WriteString(ctx, "customers/acme.json", `{"active":true}`)
contents, err := volume.FS().ReadString(ctx, "customers/acme.json")
```
--------------------------------
### CreateSandbox example with options
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Example of creating a sandbox with image, memory, CPU, and environment options. The sandbox is stopped and closed in a deferred function. The context only cancels the boot operation; cancellation after return has no effect on the running sandbox.
```go
sb, err := m.CreateSandbox(ctx, "api",
m.WithImage("python:3.12"),
m.WithMemory(512),
m.WithCPUs(2),
m.WithEnv(map[string]string{"PYTHONDONTWRITEBYTECODE": "1"}),
)
if err != nil {
return err
}
defer func() {
_ = sb.Stop(context.Background())
_ = sb.Close()
}()
```
--------------------------------
### Booting from disk images in Python
Source: https://docs.microsandbox.dev/images/overview
Provides examples for creating sandboxes from disk images using auto-detection and explicit filesystem type parameters.
```python
from microsandbox import Image, Sandbox
# Auto-detect format from file extension
sb = await Sandbox.create("custom-vm", image="./ubuntu-22.04.qcow2", cpus=2, memory=2048)
# Explicit filesystem type
sb2 = await Sandbox.create("custom-vm", image=Image.disk("./alpine.raw", fstype="ext4"), cpus=1, memory=512)
```
--------------------------------
### Snapshot::builder() usage example
Source: https://docs.microsandbox.dev/sdk/rust/snapshots
Demonstrates how to start configuring and creating a snapshot named 'baseline' from the 'api' sandbox.
```rust
let snap = Snapshot::builder("baseline")
.from_sandbox("api")
.create()
.await?;
```
--------------------------------
### Common network rule compositions
Source: https://docs.microsandbox.dev/cli/sandbox-commands
Examples of common network configurations including allowlists, blocklists, and airgapped setups.
```bash
# Allowlist: deny by default, allow specific destinations
msb run alpine --net-default deny --net-rule "allow@github.com,allow@*.githubusercontent.com"
# Blocklist: allow by default, deny specific destinations
msb run alpine --net-default allow --net-rule "deny@*.tracking.com,deny@*.ads.example"
# Airgapped: equivalent to `--net-default deny`
msb run alpine --no-net
# Airgapped except one host (allowlist with --no-net sugar)
msb run alpine --no-net --net-rule "allow@api.internal.corp"
# Public profile with DNS disabled by a higher-priority explicit rule
msb run alpine --net public --net-rule "deny@dns"
```
--------------------------------
### Create and boot from a sandbox snapshot
Source: https://docs.microsandbox.dev/sandboxes/snapshots
This workflow demonstrates stopping a running sandbox, creating a snapshot from its filesystem, and booting a new sandbox from that snapshot.
```bash
# 1. Boot a sandbox, install state, then stop it
msb run --name baseline --detach python:3.12
msb exec baseline -- pip install requests
msb stop baseline
# 2. Snapshot the stopped sandbox
msb snapshot create after-pip-install --from baseline
# 3. Boot a fresh sandbox from the snapshot
msb run --name worker --from-snapshot after-pip-install \
-- python -c "import requests; print(requests.__version__)"
```
--------------------------------
### Run a sandbox with npx
Source: https://docs.microsandbox.dev/getting-started/introduction
Quickest way to start a Debian sandbox using npx without installing the CLI first.
```bash
npx microsandbox run debian
```
--------------------------------
### Boot a sandbox from a host directory with Python SDK
Source: https://docs.microsandbox.dev/changelog/2026-06-26
Use this Python SDK example to boot a sandbox directly from a host directory using Image.bind, with no OCI pull and no overlay. The example creates a sandbox named 'dev' and runs a Python command inside it.
```python
from microsandbox import Image, Sandbox
async with await Sandbox.create(
"dev",
image=Image.bind("/srv/rootfs/python-base"),
) as sb:
output = await sb.exec("python", ["-c", "print('hello from bind rootfs')"])
print(output.stdout_text)
```
--------------------------------
### Rust custom installation
Source: https://docs.microsandbox.dev/sdk/setup
Uses the Setup builder to configure the base directory, version, verification, and force download settings.
```rust
use microsandbox::setup::Setup;
Setup::builder()
.base_dir("/opt/microsandbox")
.version("0.6.8")
.skip_verify(false)
.force(true)
.build()
.install()
.await?;
```
--------------------------------
### Start Docker in a sandbox on Windows
Source: https://docs.microsandbox.dev/examples/docker/docker-in-sandbox
Boots the docker:dind image with a 10 GiB flat root disk using PowerShell syntax.
```powershell
msb run --name docker-demo --replace `
--memory 2G `
--root-disk flat:10G `
--script start='dockerd >/tmp/dockerd.log 2>&1 &
timeout 60 sh -c "until docker info>/dev/null 2>&1;do sleep 1;done" || {
cat /tmp/dockerd.log
false
}
exec sh' `
--entrypoint start `
docker:dind
```
--------------------------------
### ExecStream usage example
Source: https://docs.microsandbox.dev/sdk/go/execution
Starts a streaming exec session with stdin pipe enabled. The returned handle must be closed after use.
```go
h, err := sb.ExecStream(ctx, "cat", nil, m.WithExecStdinPipe())
if err != nil {
return err
}
defer h.Close()
```
--------------------------------
### sftp usage example
Source: https://docs.microsandbox.dev/sdk/rust/ssh
Example of opening an SFTP session and creating a file at /tmp/hello.txt.
```rust
let sftp = client.sftp().await?;
let mut file = sftp.create("/tmp/hello.txt").await?;
```
--------------------------------
### WithPatches() usage example
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Example of using WithPatches to create a directory and write a text file into the writable layer before the VM boots.
```go
sb, err := m.CreateSandbox(ctx, "api",
m.WithImage("python"),
m.WithPatches(
m.Patch.Mkdir("/app", m.PatchOptions{}),
m.Patch.Text("/app/config.txt", "ready\n", m.PatchOptions{}),
),
)
```
--------------------------------
### network.rate_limiter() signature and example
Source: https://docs.microsandbox.dev/sdk/rust/networking
Configures network rate limits. Egress and ingress are independently optional; an omitted direction is unlimited. The limit applies on the next sandbox start. Local-only. The example shows configuring egress bandwidth, burst, and ops, plus ingress ops.
```rust
fn rate_limiter(self, f: impl FnOnce(NetworkRateLimiterBuilder) -> NetworkRateLimiterBuilder) -> Self
```
```rust
use std::time::Duration;
use microsandbox::size::SizeExt;
.network(|n| n.rate_limiter(|r| r
.egress(|r| r
.bandwidth(1.mib(), Duration::from_secs(1))
.bandwidth_burst(512.kib())
.ops(1_000, Duration::from_secs(1)))
.ingress(|r| r.ops(1_000, Duration::from_secs(1)))))
```
--------------------------------
### Start Goose with microsandbox (Windows PowerShell)
Source: https://docs.microsandbox.dev/examples/agents/goose
Windows PowerShell equivalent of the macOS/Linux command. Uses backticks for line continuation and the same Debian sandbox setup with Goose v1.44.0.
```powershell
msb run -t --name goose-demo --replace `
--cpus 2 --memory 2G --root-disk 3G `
--mount-dir ./my-project:/workspace:rw `
--workdir /workspace `
debian:bookworm-slim -- sh -lc '
apt-get update &&
apt-get install -y --no-install-recommends ca-certificates curl bzip2 git &&
curl -fsSL https://github.com/aaif-goose/goose/releases/download/v1.44.0/download_cli.sh |
GOOSE_BIN_DIR=/usr/local/bin GOOSE_VERSION=v1.44.0 CONFIGURE=false bash &&
exec goose session
'
```
--------------------------------
### start()
Source: https://docs.microsandbox.dev/sdk/rust/sandbox
Starts the sandbox. The returned local handle is attached; a cloud handle does not own the service-managed VM.
```APIDOC
## start()
### Description
Start the sandbox. The returned local handle is attached; a cloud handle does not own the service-managed VM.
### Method Signature
```rust
start()
```
### Returns
`Result`
```
--------------------------------
### Use msb run with --copy, --copy-dir, --mkdir, --rm flags and msb copy
Source: https://docs.microsandbox.dev/changelog/2026-05-29
Prepares a fresh sandbox in one step by copying files and directories, creating a directory, and removing a file, then shows host-to-sandbox and sandbox-to-sandbox copies. Server commands are separated with `&&` in the first block.
```bash
msb run alpine \
--copy ./config.toml:/etc/app/config.toml \
--copy-dir ./certs:/etc/app/certs \
--mkdir /var/cache/app \
--rm /etc/motd
msb copy ./local.txt devbox:/tmp/local.txt
msb copy devbox:/tmp/a otherbox:/tmp/a
```
--------------------------------
### sb.exec_stream() signature and example
Source: https://docs.microsandbox.dev/sdk/rust/execution
Defines the async exec_stream method that runs a command with streaming output. Returns an ExecHandle that emits stdout, stderr, started, and exit events as they happen, rather than buffering everything until the command finishes. The example tails a log file and prints stdout chunks until the process exits.
```rust
async fn exec_stream(
&self,
cmd: impl Into,
args: impl IntoIterator- >,
) -> MicrosandboxResult
```
```rust
use microsandbox::ExecEvent;
let mut handle = sb.exec_stream("tail", ["-f", "/var/log/app.log"]).await?;
while let Some(event) = handle.recv().await {
match event {
ExecEvent::Stdout(chunk) => print!("{}", String::from_utf8_lossy(&chunk)),
ExecEvent::Exited { code } => { println!("exited {code}"); break; }
_ => {}
}
}
```
--------------------------------
### SnapshotHandle::open()
Source: https://docs.microsandbox.dev/sdk/rust/snapshots
Opens the underlying artifact metadata, upgrading the handle to a full Snapshot. Equivalent to Snapshot::open(self.path()). Example shows getting a handle and calling open().
```rust
async fn open(&self) -> MicrosandboxResult
```
```rust
let h = Snapshot::get("baseline").await?;
let snap = h.open().await?;
snap.verify().await?;
```
--------------------------------
### Configure init with custom arguments and environment
Source: https://docs.microsandbox.dev/sandboxes/bootstrap
Examples of passing specific init commands, arguments, and environment variables to the sandbox.
```typescript
await using sb = await Sandbox.builder("worker")
.image("ghcr.io/superradcompany/debian-systemd:12")
.initWith("/lib/systemd/systemd", (i) => i
.args(["--unit=multi-user.target"])
.env("container", "microsandbox"))
.create();
```
```rust
let sb = Sandbox::builder("worker")
.image("ghcr.io/superradcompany/debian-systemd:12")
.init_with("/lib/systemd/systemd", |i| i
.args(["--unit=multi-user.target"])
.env("container", "microsandbox"))
.create()
.await?;
```
```python
from microsandbox import InitConfig, Sandbox
sb = await Sandbox.create(
"worker",
image="ghcr.io/superradcompany/debian-systemd:12",
init=InitConfig(
cmd="/lib/systemd/systemd",
args=("--unit=multi-user.target",),
env={"container": "microsandbox"},
),
)
```
```go
sb, err := m.CreateSandbox(ctx, "worker",
m.WithImage("ghcr.io/superradcompany/debian-systemd:12"),
m.WithInit(m.Init.Cmd("/lib/systemd/systemd",
m.InitOptions{
Args: []string{"--unit=multi-user.target"},
Env: map[string]string{"container": "microsandbox"},
},
)),
)
```
```bash
msb run ghcr.io/superradcompany/debian-systemd:12 \
--init /lib/systemd/systemd \
--init-arg --unit=multi-user.target \
--init-env container=microsandbox \
-- bash
```
--------------------------------
### Run a sandbox on Windows with msb run
Source: https://docs.microsandbox.dev/changelog/2026-06-26
Use this command to start a sandbox on Windows, which is now supported as a first-class host. The example maps host port 8080 to guest port 8080 and uses the python:3.12 image.
```bash
msb run --name devbox -p 8080:8080 python:3.12
```
--------------------------------
### Initialize Sandbox with Python SDK
Source: https://docs.microsandbox.dev/changelog/2026-04-17
Demonstrates creating a sandbox instance and executing a shell command using the new Python SDK.
```python
async with await Sandbox.create("my-sandbox", image="alpine") as sb:
out = await sb.shell("echo hello")
print(out.stdout_text)
```
--------------------------------
### SnapshotHandle::remove()
Source: https://docs.microsandbox.dev/sdk/rust/snapshots
Removes this snapshot. Delegates to Snapshot::remove(self.digest(), force). The force parameter, when true, removes even if the snapshot has indexed children. Example shows getting a handle and calling remove(false).
```rust
async fn remove(&self, force: bool) -> MicrosandboxResult<()>
```
```rust
let h = Snapshot::get("baseline").await?;
h.remove(false).await?;
```
--------------------------------
### msb run command examples
Source: https://docs.microsandbox.dev/cli/sandbox-commands
Examples of running ephemeral and persistent sandboxes, configuring volumes and ports, and managing background processes.
```bash
# Ephemeral: runs and cleans up
msb run python -- python -c "print('hello')"
# Named: persists after exit
msb run --name devbox ubuntu -- bash
# With volumes, ports, and environment
msb run --name api \
-v ./src:/app \
-v pydata:/data \
-p 8000:8000 \
-e DEBUG=true \
--label user.id=alice \
-w /app \
python
# Detached: run the resolved command in the background
msb run -d --name worker python -- python worker.py
msb logs -f worker
# Boot an idle sandbox for later exec calls
msb create --name devbox python
msb exec devbox -- python -c "print('hello')"
# Publish on all IPv4 host interfaces instead of the default 127.0.0.1
msb run --name public-api -p 0.0.0.0:8000:8000 python
```
--------------------------------
### Image::inspect() - Get full detail for a cached image
Source: https://docs.microsandbox.dev/sdk/rust/images
Returns full detail for a cached image: handle metadata, parsed OCI config fields, and layer metadata. The example prints each layer's position and diff_id.
```rust
async fn inspect(reference: &str) -> MicrosandboxResult
```
```rust
let detail = Image::inspect("python:3.12").await?;
for layer in &detail.layers {
println!("{} {}", layer.position, layer.diff_id);
}
```
--------------------------------
### Full example of global config.json
Source: https://docs.microsandbox.dev/configuration
Complete example of the global configuration file. All fields are optional; a missing file or empty JSON object is equivalent to using the defaults. The example includes settings for home, log level, deployment profile, database, paths, sandbox defaults, runtime, registries, SSH, metrics, and profiles.
```json
{
"home": "/custom/path/.microsandbox",
"log_level": "info",
"deployment_profile": "multi-tenant",
"database": {
"url": "sqlite:///tmp/msb.db",
"max_connections": 10,
"connect_timeout_secs": 30,
"busy_timeout_secs": 30
},
"paths": {
"msb": "/usr/local/bin/msb",
"libkrunfw": "/usr/local/lib/libkrunfw.so",
"cache": "/mnt/fast/msb-cache",
"sandboxes": null,
"volumes": null,
"snapshots": null,
"logs": null,
"secrets": null
},
"sandbox_defaults": {
"cpus": 2,
"memory_mib": 1024,
"cpu_placement": "auto",
"placement_profile": "latency",
"thp": "madvise",
"oci": {
"root_disk": {
"kind": "flat",
"size_mib": 8192,
"clone": "auto"
}
},
"shell": "/bin/bash",
"workdir": "/app"
},
"runtime": {
"placement_profiles": {
"latency": {
"numa": { "mode": "prefer_single" },
"memory": { "mode": "follow_cpu" }
}
},
"block_writeback": {
"mode": "auto"
}
},
"registries": {
"ca_certs": "/path/to/corporate-ca.pem",
"hosts": {
"ghcr.io": {
"auth": {
"username": "octocat",
"store": "keyring"
}
},
"registry.example.com": {
"insecure": true,
"auth": {
"username": "deploy",
"password_env": "REGISTRY_TOKEN"
}
},
"docker.io": {
"auth": {
"username": "user",
"secret_name": "dockerhub-token"
}
}
}
},
"ssh": {
"inactivity_timeout_secs": 600
},
"metrics": {
"capacity": 4096
},
"active_profile": "prod",
"profiles": {
"prod": {
"backend": "cloud",
"api_key_ref": "env:MSB_API_KEY"
},
"local": {
"backend": "local"
}
}
}
```
--------------------------------
### Start Goose with microsandbox (macOS & Linux)
Source: https://docs.microsandbox.dev/examples/agents/goose
Launches a Debian sandbox with a writable host-directory mount and installs Goose v1.44.0. On first launch Goose asks about usage data and provider configuration. The mount is local-only; for cloud use the isolated-copy alternative.
```sh
msb run -t --name goose-demo --replace \
--cpus 2 --memory 2G --root-disk 3G \
--mount-dir ./my-project:/workspace:rw \
--workdir /workspace \
debian:bookworm-slim -- sh -lc '
apt-get update &&
apt-get install -y --no-install-recommends ca-certificates curl bzip2 git &&
curl -fsSL https://github.com/aaif-goose/goose/releases/download/v1.44.0/download_cli.sh |
GOOSE_BIN_DIR=/usr/local/bin GOOSE_VERSION=v1.44.0 CONFIGURE=false bash &&
exec goose session
'
```
--------------------------------
### Start(ctx)
Source: https://docs.microsandbox.dev/sdk/go/sandbox
Boots a stopped sandbox. The returned local handle is attached; a cloud handle does not own the service-managed VM.
```APIDOC
## Start(ctx)
### Description
Boot a stopped sandbox. The returned local handle is attached; a cloud handle does not own the service-managed VM.
### Method
Start(ctx)
### Parameters
- ctx (context.Context) - Required - The context for the operation.
### Returns
- (*Sandbox, error)
```
--------------------------------
### Open an SSH client example
Source: https://docs.microsandbox.dev/sdk/go/ssh
Example of opening an SSH client with specific user and terminal options.
```go
client, err := sb.SSH().OpenClient(ctx,
m.WithSSHUser("app"),
m.WithSSHTerm("xterm-256color"),
)
if err != nil {
return err
}
defer client.Close(ctx)
```
--------------------------------
### create() usage example
Source: https://docs.microsandbox.dev/sdk/typescript/sandbox
Example of building and booting a sandbox with a name, image, and detached mode, then detaching the handle.
```typescript
const sandbox = await Sandbox.builder("worker")
.image("python")
.detached(true)
.create();
await sandbox.detach();
```
--------------------------------
### OpenAPI specification for GET /v1/sandboxes/by-name/{name}
Source: https://docs.microsandbox.dev/api-reference/endpoints/sandboxes/get-a-sandbox-by-name
YAML OpenAPI 3.1.0 definition for the endpoint. It specifies the path parameter 'name', security via API key, and response schemas including success (200) and error responses (401, 404) with example error payloads.
```yaml
openapi: 3.1.0
info:
title: microsandbox cloud API
description: >-
REST API for microsandbox cloud: sandbox and volume lifecycle, organization
context, quotas, usage, and audit events, authenticated with an organization
API key.
version: 0.1.0
servers:
- url: https://api.microsandbox.dev
security:
- api_key: []
paths:
/v1/sandboxes/by-name/{name}:
get:
tags:
- Sandboxes
summary: Get a sandbox by name
description: Retrieve one sandbox by its organization-scoped name.
operationId: get_by_name
parameters:
- name: name
in: path
description: Sandbox name (unique within the org)
required: true
schema:
type: string
responses:
'200':
description: Sandbox details
content:
application/json:
schema:
$ref: '#/components/schemas/SandboxResponse'
'401':
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
example:
error:
code: invalid_api_key
message: unauthorized
details: null
'404':
description: Sandbox not found
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
example:
error:
code: sandbox_not_found
message: resource not found
details: null
security:
- api_key: []
components:
schemas:
SandboxResponse:
type: object
description: >-
The API view of a [`Sandbox`]: an explicit allowlist of user-facing
fields.
Internal columns (registry selection, sync bookkeeping, resolved refs)
never
appear; the resolved spec surfaces only as the curated
[`SandboxSpecResponse`].
required:
- id
- org_id
- name
- slug
- status
- ephemeral
- created_at
properties:
created_at:
type: string
format: date-time
ephemeral:
type: boolean
id:
type: string
format: uuid
last_failure_message:
type:
- string
- 'null'
description: Human-readable reason for the last failure.
name:
type: string
org_id:
type: string
format: uuid
slug:
type: string
spec:
oneOf:
- type: 'null'
- $ref: '#/components/schemas/SandboxSpecResponse'
description: Curated projection of the resolved spec; absent until resolved.
started_at:
type:
- string
- 'null'
format: date-time
description: Latest run's start time; `null` if the sandbox has never run.
status:
$ref: '#/components/schemas/SandboxStatus'
status_reason:
oneOf:
- type: 'null'
- $ref: '#/components/schemas/SandboxStatusReason'
description: Scheduler condition while `status` is `starting`.
stopped_at:
type:
- string
- 'null'
format: date-time
description: Latest run's stop time; `null` while open or never run.
ErrorResponse:
type: object
description: Error envelope returned by every non-2xx response.
required:
- error
properties:
error:
type: object
required:
- code
- message
properties:
code:
type: string
description: Stable machine-readable error code, e.g. `invalid_api_key`.
message:
type: string
description: Human-readable description of the error.
details:
type:
- object
- 'null'
description: Optional structured context for the error.
SandboxSpecResponse:
type: object
description: >-
A curated, user-facing projection of a sandbox's resolved spec. Built
from
[`ResolvedSandboxSpec`]; omits every internal resolution (secret
```
--------------------------------
### Go skip download installation
Source: https://docs.microsandbox.dev/sdk/setup
Uses WithSkipDownload to ensure the runtime is pre-provisioned without attempting a download.
```go
import m "github.com/superradcompany/microsandbox/sdk/go"
// Do not download. Return an error if the runtime was not pre-provisioned.
if err := m.EnsureInstalled(ctx, m.WithSkipDownload()); err != nil {
return err
}
```
--------------------------------
### Run Gemini CLI in a microVM
Source: https://docs.microsandbox.dev/examples/agents/gemini-cli
Starts a disposable Node.js microVM with the Gemini CLI installed and launches the interactive TUI. The project is mounted from the host as a writable directory; authentication and settings live on the sandbox's root disk. The scoped package @google/gemini-cli@0.52.0 is pinned exactly as shown.
```sh
msb run -t --name gemini-demo --replace \
--cpus 2 --memory 2G --root-disk 4G \
--mount-dir ./my-project:/workspace:rw \
--workdir /workspace \
node:24-bookworm-slim -- sh -lc '
apt-get update &&
apt-get install -y --no-install-recommends ca-certificates git &&
npm install -g @google/gemini-cli@0.52.0 &&
exec gemini
'
```
```powershell
msb run -t --name gemini-demo --replace `
--cpus 2 --memory 2G --root-disk 4G `
--mount-dir ./my-project:/workspace:rw `
--workdir /workspace `
node:24-bookworm-slim -- sh -lc '
apt-get update &&
apt-get install -y --no-install-recommends ca-certificates git &&
npm install -g @google/gemini-cli@0.52.0 &&
exec gemini
'
```
--------------------------------
### Boot a sandbox from a snapshot (TypeScript, Rust, Python, Go, CLI)
Source: https://docs.microsandbox.dev/sandboxes/snapshots
Shows how to create a sandbox from a snapshot in each supported language and the CLI. The snapshot pins its image, so this is mutually exclusive with specifying an image source. Booting validates the snapshot, resolves the pinned image, and gives the new sandbox its own writable copy.
```typescript
import { Sandbox } from "microsandbox";
const sb = await Sandbox.builder("worker")
.fromSnapshot("after-pip-install")
.create();
```
```rust
use microsandbox::Sandbox;
let sb = Sandbox::builder("worker")
.from_snapshot("after-pip-install")
.create()
.await?;
```
```python
from microsandbox import Sandbox
# `from_snapshot=` is a peer of `image=` and mutually exclusive with it
sb = await Sandbox.create("worker", from_snapshot="after-pip-install")
```
```go
sb, err := m.CreateSandbox(ctx, "worker",
m.WithFromSnapshot("after-pip-install"),
)
```
```bash
msb run --name worker --from-snapshot after-pip-install -- python -V
```
--------------------------------
### Require and install microsandbox
Source: https://docs.microsandbox.dev/sdk/ruby/sandbox
Requires the microsandbox library and installs the native extension if not already installed. Use after installing the gem.
```ruby
require "microsandbox"
Microsandbox.install unless Microsandbox.installed?
```