---
title: sandbox
description: Declare a Linux sandbox in a luna, and run commands, processes and files in it with ctx.sandboxes.
related:
  - /files-and-code/run-a-sandbox
  - /files-and-code/run-processes-in-a-sandbox
  - /files-and-code/connect-to-a-sandbox
---

`sandbox` declares a Linux machine of the luna's own under the luna type's `sandboxes` option. A handler drives it as `ctx.sandboxes.<name>`, and it starts on first use.

```ts luna/lunas/user.ts
import { defineLuna, sandbox, t } from "luna";

export const User = defineLuna({
  name: "User",
  key: { id: t.string() },
  sandboxes: {
    dev: sandbox({ image: "ghcr.io/acme/tools@sha256:<DIGEST>", memory: "1GB" }),
  },
  handlers: (h) => ({
    test: h({}, async (ctx) => {
      const r = await ctx.sandboxes.dev.exec("npm test", { cwd: "/home/app" });
      return { ok: r.exitCode === 0, out: r.stdout };
    }),
  }),
});
```

## Reference

### sandbox(options)

| Prop | Type | Default | Description |
| - | - | - | - |
| `image` | `string` | - | An OCI image pinned by digest, such as `ghcr.io/acme/tools@sha256:…`, and when the digest names an index, the build for the machine's architecture is used. |
| `cpu?` | `number \| { max: number; default?: number }` | `1` | Virtual CPUs, and with `max`, each instance starts with `default` and can be resized from 1 to `max`. |
| `memory?` | `string \| { max: string; default?: string }` | `"512MB"` | Memory as `"512MB"` or `"2GB"`, and with `max`, each instance starts with `default` and can be resized from `"256MB"` to `max`. |
| `disk?` | `string` | `"4GB"` | The size of `/home`, and of the writable layer over the image. |
| `idle?` | `string \| number` | `"5m"` | Powers it off after this long with no request. |
| `persist?` | `"none" \| "filesystem" \| "freeze"` | `"filesystem"` | What is kept when it stops: nothing, its disks, or its disks with its memory and processes where that can be done. |
| `network?` | `"none" \| "public" \| { allow: string[] }` | `"none"` | What it can reach: nothing, as it has no network device, the internet, or only the names listed, such as `"*.github.com"`. |
| `privateNetwork?` | `boolean` | `false` | Puts it on a network with this luna's other such sandboxes, as `<name>.sandbox.internal`. |
| `ports?` | `number[]` | - | The ports the luna reaches with `port(n)`. |

Sizes take `MB`, `GB` or `TB`, such as `"1.5GB"`.

### Sandbox

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The instance's name. |
| `files` | `SandboxFiles` | - | The files of its `/home` volume. |
| `exec(command, opts?)` | `Promise<ExecResult>` | - | Runs a command and waits for it, where a string goes to `/bin/sh -c` and an array runs as it is. |
| `spawn(command?, opts?)` | `Promise<SandboxProcess>` | - | Starts a process that runs on after this call, and with no command, a login shell. |
| `attach(name)` | `SandboxProcess` | - | A process started before, by its name. |
| `processes()` | `Promise<ProcessInfo[]>` | - | Its processes: those running, and those that ended whose output is kept. |
| `port(n)` | `SandboxPort` | - | A declared port, to send HTTP requests to or hand to an app. |
| `terminal(opts?)` | `Promise<SandboxTicket>` | - | A ticket for an app to connect to a process as a terminal, over a WebSocket. |
| `ssh()` | `Promise<SandboxSsh>` | - | How to reach it over SSH, which the luna's `onSshConnect` hook allows. |
| `status()` | `Promise<SandboxStatus>` | - | Its state, size and last use, without starting it. |
| `list()` | `Promise<SandboxStatus[]>` | - | Every instance of this declaration the luna has. |
| `instance(name, size?)` | `Sandbox` | - | Another instance of this declaration, which starts on first use with `size` if it is new. |
| `fork(name)` | `Promise<Sandbox>` | - | A new instance with a copy of this one's disks as they are now. |
| `resize(size)` | `Promise<{ cpu: number; memoryMib: number }>` | - | Sets its size, at once if it runs or for its next start, for a resizable declaration. |
| `stop()` | `Promise<void>` | - | Powers it off now, keeping what `persist` says. |
| `freeze()` | `Promise<void>` | - | Saves its memory and processes with its disks, so the next use carries on from there. |
| `destroy()` | `Promise<void>` | - | Deletes it and everything kept of it. |

### SandboxPort

| Prop | Type | Default | Description |
| - | - | - | - |
| `port` | `number` | - | The port. |
| `fetch(path, init?)` | `Promise<Response>` | - | Sends an HTTP request with `method`, `headers`, `body` and `timeout`, wakes the sandbox for it, and returns up to 16 MiB. |
| `connect()` | `Promise<SandboxTicket>` | - | A ticket for an app to reach the port over a WebSocket whose binary messages are the bytes each way. |
| `publicUrl()` | `Promise<string>` | - | A public HTTPS address for the port while the sandbox runs, the same every time, where your plan allows it. |
| `revokePublicUrl()` | `Promise<void>` | - | Takes the public address down. |

A port works whether or not the sandbox has a network.

### SandboxFiles

Paths are relative to `/home`, or absolute within it.

| Prop | Type | Default | Description |
| - | - | - | - |
| `read(path, opts?)` | `Promise<Uint8Array>` | - | A file's bytes, from `opts.offset` for `opts.length` bytes. |
| `text(path)` | `Promise<string>` | - | A file as UTF-8 text. |
| `write(path, data, opts?)` | `Promise<number>` | - | Writes a file with any directories it needs, with `opts.mode`, and returns its size. |
| `list(path?)` | `Promise<FileInfo[]>` | - | The entries of a directory, `"."` by default. |
| `stat(path)` | `Promise<FileInfo \| null>` | - | What is at `path`, or `null`. |
| `remove(path, opts?)` | `Promise<boolean>` | - | Removes a file, or a directory with `opts.recursive`, and says whether there was one. |
| `mkdir(path)` | `Promise<void>` | - | Makes a directory. |
| `copyTo(bucket, from, to?, opts?)` | `Promise<void>` | - | Copies a file of up to 256 MiB to a bucket, with `opts.contentType`. |
| `copyFrom(bucket, from, to?)` | `Promise<void>` | - | Copies an object from a bucket into the volume, waking the sandbox. |

### SandboxProcess

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The process's name in its sandbox. |
| `at` | `{ stdout: number; stderr: number }` | - | How far its output has been read, which you may set to read again from there. |
| `read(opts?)` | `Promise<ProcessOutput>` | - | What it wrote since the last read, waiting up to `opts.wait` and at most a minute, `opts.max` bytes at most. |
| `text(opts?)` | `Promise<{ stdout: string; stderr: string; lost: number; exit: ProcessExit \| null }>` | - | `read`, as text. |
| `write(data)` | `Promise<void>` | - | Writes to its input. |
| `end()` | `Promise<void>` | - | Closes its input. |
| `resize(cols, rows)` | `Promise<void>` | - | Sets its terminal's size. |
| `kill(signal?)` | `Promise<void>` | - | Sends it and everything it started a signal, `"TERM"` by default. |
| `wait(timeout?)` | `Promise<ProcessExit \| null>` | - | How it ended, waiting up to `timeout`, `"1m"` by default and at most, and `null` if it still runs. |
| `remove()` | `Promise<void>` | - | Ends it if it runs, and forgets it and its output. |

### ExecOptions and ExecResult

| Prop | Type | Default | Description |
| - | - | - | - |
| `cwd?` | `string` | `"/home"` | The working directory. |
| `env?` | `Record<string, string>` | - | Environment variables. |
| `timeout?` | `string \| number` | `"5m"` | Stops the command and everything it started after this long. |
| `stdin?` | `string \| Uint8Array` | - | Written to its standard input. |

`exec` returns an `ExecResult`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `exitCode` | `number \| null` | - | Its exit code, or `null` if a signal ended it. |
| `stdout` | `string` | - | Its standard output. |
| `stderr` | `string` | - | Its standard error. |
| `timedOut` | `boolean` | - | Whether `timeout` stopped it. |
| `truncated` | `boolean` | - | Whether output past 16 MiB on either stream was dropped. |

### SpawnOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `name?` | `string` | - | A name to `attach` by, unique in the sandbox, of letters, digits, `-`, `_` and `.`, and without one it gets a name of its own. |
| `pty?` | `boolean \| { cols: number; rows: number }` | - | Runs it on a terminal, 80 by 24 for `true`, with its output and errors together. |
| `cwd?` | `string` | `"/home"` | The working directory. |
| `env?` | `Record<string, string>` | - | Environment variables. |
| `user?` | `string` | `root` | A user of the image to run as. |
| `keepAwake?` | `boolean` | `false` | Keeps the sandbox, and its luna, awake while it runs. |
| `buffer?` | `string` | `"1MB"` | How much of its output is kept to read back, at most `"64MB"`. |

### TerminalOptions

`TerminalOptions` takes `cwd`, `env`, `user`, `keepAwake` and `buffer` as in `SpawnOptions`, and these.

| Prop | Type | Default | Description |
| - | - | - | - |
| `name?` | `string` | - | The process to join, started first if it does not run, and kept when the connection goes, while one with no name ends with its connection. |
| `command?` | `string \| string[]` | - | What to start, a login shell by default. |
| `pty?` | `boolean \| { cols: number; rows: number }` | `80 by 24` | Its terminal's size to begin with, or `false` for none. |
| `replay?` | `number` | - | How many bytes of what a named process wrote before are sent first, all that is kept by default. |

### SandboxTicket and SandboxSsh

| Prop | Type | Default | Description |
| - | - | - | - |
| `path` | `string` | - | The path to open as a WebSocket on your app's URL, such as `/_luna/sandbox/connect?ticket=…`. |
| `ticket` | `string` | - | The ticket. |
| `expiresMs` | `number` | - | When it stops working, a minute after it was made, in milliseconds since the epoch. |

A ticket works once. `ssh()` returns a `SandboxSsh`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `host` | `string` | - | The host to connect to. |
| `port` | `number` | - | The port to connect to. |
| `user` | `string` | - | The SSH login name, which names this sandbox and is the same every time. |
| `hostKey` | `string` | - | The host key, as `ssh-ed25519 AAAA…`, for a `known_hosts` line of `[host]:port` and this. |
| `command` | `string` | - | The command to connect, `ssh -p <port> <user>@<host>`. |

### SandboxStatus and SandboxSize

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The instance's name. |
| `state` | `"running" \| "asleep" \| "frozen" \| "none"` | - | Running, stopped with its disks, stopped with its memory and processes too, or no such sandbox. |
| `cpu` | `number` | - | The CPUs it has, or will start with. |
| `memoryMib` | `number` | - | The memory it has, or will start with, in MiB. |
| `max?` | `{ cpu: number; memoryMib: number }` | - | The most it can be resized to, for a resizable declaration. |
| `createdMs?` | `number` | - | When it was made. |
| `lastUsedMs?` | `number` | - | When it was last used. |
| `diskUsedBytes?` | `number` | - | What its disks hold. |
| `startedMs?` | `number` | - | When it started, while it runs. |
| `connections?` | `number` | - | The connections open to it, while it runs. |
| `stoppedBy?` | `"idle" \| "code" \| "luna" \| "crash"` | - | Why it last stopped: no use, its luna's code, its luna sleeping or moving, or it ended by itself. |
| `stoppedMs?` | `number` | - | When it last stopped. |

Times are milliseconds since the epoch. A `SandboxSize` is `{ cpu?: number; memory?: string }`, with memory as `"2GB"`.

### ProcessInfo, ProcessOutput and ProcessExit

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | Its name. |
| `pid` | `number` | - | Its process id. |
| `pty` | `boolean` | - | Whether it runs on a terminal. |
| `command` | `string` | - | What it runs. |
| `startedMs` | `number` | - | When it started, in milliseconds since the epoch. |
| `keepAwake` | `boolean` | - | Whether it keeps the sandbox awake. |
| `running` | `boolean` | - | Whether it still runs. |
| `exit` | `ProcessExit \| null` | - | How it ended. |
| `stdout` | `number` | - | How many bytes it wrote to standard output. |
| `stderr` | `number` | - | How many bytes it wrote to standard error. |

`read` returns a `ProcessOutput`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `stdout` | `Uint8Array` | - | Standard output since the last read. |
| `stderr` | `Uint8Array` | - | Standard error since the last read. |
| `lost` | `number` | - | Bytes written before these that are no longer kept, because its buffer was full. |
| `exit` | `ProcessExit \| null` | - | How it ended, once all it wrote has been read. |

A `ProcessExit` is `{ exitCode: number | null; signal: number | null }`: its exit code, or the signal that ended it.

### FileInfo

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The entry's name. |
| `type` | `"file" \| "dir" \| "symlink"` | - | What it is. |
| `size` | `number` | - | Its size in bytes. |
| `mode` | `number` | - | Its permission bits. |
| `mtimeMs` | `number` | - | When it last changed, in milliseconds since the epoch. |

## Good to know

- An image with a tag and no digest is refused when the luna type is defined. An image unpacks to at most 32 GiB.
- A process does not keep an idle sandbox running unless it was spawned with `keepAwake`.
- A named process runs until it ends or is killed, and its output stays readable after.
- A command that must outlive the call runs with `spawn`, and later calls read it with `attach`.
- Reading its files works while the sandbox is asleep.
- `resize` is refused when the sandbox uses more memory than it would be left with. A sandbox is billed at the size it is set to.
- Private addresses are never reachable from a sandbox. `internet: false` on the luna type also turns the internet off for its sandboxes.
- A request for more CPU, memory or disk than Luna allows is refused. Your plan also caps how many sandboxes run at once. See [Limits](/platform/limits).

## Examples

### Run a dev server and read its output

```ts luna/lunas/user.ts
serve: h({}, async (ctx) => {
  const p = await ctx.sandboxes.dev.spawn("npm run dev", { name: "server", cwd: "/home/app", keepAwake: true });
  return p.name;
}),
logs: h({}, async (ctx) => {
  const out = await ctx.sandboxes.dev.attach("server").text({ wait: "5s" });
  return { text: out.stdout, lost: out.lost, exit: out.exit };
}),
```

### Write and read files

```ts luna/lunas/user.ts
files: h({}, async (ctx) => {
  const files = ctx.sandboxes.dev.files;
  await files.write("app/notes.txt", "hello");
  const list = await files.list("app");
  return { text: await files.text("app/notes.txt"), names: list.map((f) => f.name) };
}),
```

### Make a sandbox resizable

```ts luna/lunas/user.ts
sandboxes: {
  dev: sandbox({
    image: "ghcr.io/acme/tools@sha256:<DIGEST>",
    cpu: { max: 4 },
    memory: { max: "8GB", default: "1GB" },
    disk: "10GB",
    network: "public",
    ports: [3000],
  }),
},
```

```ts luna/lunas/user.ts
grow: h({}, async (ctx) => ctx.sandboxes.dev.resize({ cpu: 4, memory: "8GB" })),
```

### Call a server in the sandbox

```ts luna/lunas/user.ts
health: h({}, async (ctx) => (await ctx.sandboxes.dev.port(3000).fetch("/health")).status),
```

### Hand an app a terminal

```ts luna/lunas/user.ts
shell: h({}, async (ctx) => ctx.sandboxes.dev.terminal({ name: "shell", cwd: "/home/app" })),
```

The app opens the ticket's `path` on your app's URL as a WebSocket within a minute.

### Try a change on a copy

```ts luna/lunas/user.ts
branch: h({ args: { name: t.string() } }, async (ctx, { name }) => {
  const copy = await ctx.sandboxes.dev.fork(name);
  return (await copy.exec(["git", "status"])).stdout;
}),
```
