> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Images and builds

> Choose what a sandbox starts from: Fibre's default image, any public image, an image you build on Fibre from a Dockerfile, or an image from your own registry.

An **image** is the set of files a sandbox starts with: the operating system, the languages and tools, and
anything else installed in advance. If you have used Docker, it is the same idea, and the same images work.

You choose a sandbox's image with the `image` option when you create it. There are several kinds to choose from:

| Start from | `image` | When |
| - | - | - |
| Fibre's default image | leave it out | Most agents and scripts: Python, Node, git and a browser are ready |
| A public image | `"python:3.12-slim"`, `"node:22"`, `"ubuntu:24.04"` | A specific language version or distribution |
| **An image you build on Fibre** | the `image` of a finished build | Your app or your agent's toolchain, from your own Dockerfile |
| A private image | `"ghcr.io/acme/agent:1.4"` | Your registry, with [credentials](https://docs.fibre.dev/setup/registries.md) stored once |

> [!NOTE]
>
> If you plan to **run commands in** the sandbox (rather than use it to serve an app), add `"ready": "process"`.
> Without it, Fibre runs the image's own startup command and waits for it to answer on its port. See
> [sizes and installed tools](https://docs.fibre.dev/sandboxes/sizes.md#bring-your-own-image) for the details.

## Build an image from a Dockerfile

A **Dockerfile** is a recipe for an image: start from this base, install these packages, copy in this code. Fibre
can build an image from a Dockerfile for you. **You do not need Docker on your machine, or a registry to store
the result.** You send the Dockerfile and the files it uses, Fibre builds the image, and the image is then ready
to use in your account's sandboxes.

This example builds a small web API written with FastAPI, a popular Python framework, and then runs it in a
sandbox that serves it at a public address.

**1. Write the app and its Dockerfile**

```bash title="Terminal" run theme={null}
mkdir -p hello-api
cat > hello-api/main.py <<'EOF'
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def hello():
    return {"message": "built and served on Fibre"}
EOF

cat > hello-api/Dockerfile <<'EOF'
FROM python:3.12-slim
RUN pip install --no-cache-dir fastapi uvicorn
WORKDIR /app
COPY main.py .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
EOF
```

```typescript title="TypeScript" run theme={null}
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { Fibre, Sandbox } from "@fibre-dev/sdk";

mkdirSync("hello-api", { recursive: true });
writeFileSync("hello-api/main.py", [
  "from fastapi import FastAPI",
  "",
  "app = FastAPI()",
  "",
  '@app.get("/")',
  "def hello():",
  '    return {"message": "built and served on Fibre"}',
].join("\n") + "\n");

writeFileSync("hello-api/Dockerfile", [
  "FROM python:3.12-slim",
  "RUN pip install --no-cache-dir fastapi uvicorn",
  "WORKDIR /app",
  "COPY main.py .",
  'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]',
].join("\n") + "\n");
```

```python title="Python" run theme={null}
from pathlib import Path

from fibre import Fibre, Sandbox

Path("hello-api").mkdir(exist_ok=True)
Path("hello-api/main.py").write_text("\n".join([
    "from fastapi import FastAPI",
    "",
    "app = FastAPI()",
    "",
    '@app.get("/")',
    "def hello():",
    '    return {"message": "built and served on Fibre"}',
]) + "\n")

Path("hello-api/Dockerfile").write_text("\n".join([
    "FROM python:3.12-slim",
    "RUN pip install --no-cache-dir fastapi uvicorn",
    "WORKDIR /app",
    "COPY main.py .",
    'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]',
]) + "\n")
```

**2. Send it to Fibre**

Send the folder containing the Dockerfile as a single archive. (This folder is called the **build context**: the
Dockerfile can only use files that are inside it.)

```bash title="curl" run capture=BUILD=.id theme={null}
tar -C hello-api -czf - . | curl -sS -X POST "$FIBRE_API_URL/v1/builds" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/x-tar" --data-binary @-
```

```typescript title="TypeScript" run theme={null}
const fibre = new Fibre();
const context = execFileSync("tar", ["-C", "hello-api", "-czf", "-", "."]);
let build = await fibre.json<{ id: string; status: string; image: string | null }>("POST", "/v1/builds", {
  raw: context,
  headers: { "content-type": "application/x-tar" },
});
console.log(build.id, build.status); // 7c1e… building
```

```python title="Python" run theme={null}
import subprocess

fibre = Fibre()
context = subprocess.run(["tar", "-C", "hello-api", "-czf", "-", "."], capture_output=True, check=True).stdout
build = fibre.json("POST", "/v1/builds", content=context, headers={"content-type": "application/x-tar"})
print(build["id"], build["status"])  # 7c1e… building
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "id": "…",
>   "status": "…"
> }
> ```

The build runs on Fibre while you wait or do something else. This one takes about 15 seconds. **If you send exactly
the same files and Dockerfile as an earlier build, Fibre does not build again.** It answers straight away with
`"status": "succeeded"`, the earlier image, and `"cached": true`.

**3. Follow the build**

```bash title="curl" run theme={null}
curl -sSN "$FIBRE_API_URL/v1/builds/$BUILD/logs?follow=1" -H "Authorization: Bearer $FIBRE_API_KEY" | tail -n 1
```

```typescript title="TypeScript" run theme={null}
while (build.status === "building") {
  await new Promise((r) => setTimeout(r, 3000));
  build = await fibre.json("GET", `/v1/builds/${build.id}`);
}
console.log(build.status, build.image); // succeeded build/…
```

```python title="Python" run theme={null}
import time

while build["status"] == "building":
    time.sleep(3)
    build = fibre.json("GET", f"/v1/builds/{build['id']}")
print(build["status"], build["image"])  # succeeded build/…
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> "status":"succeeded"
> ```

The build log streams one JSON line for each piece of build output, followed by an `end` line with the final
status. It works just like a [command's output](https://docs.fibre.dev/sandboxes/running-commands.md#the-output-stream).

**4. Run it**

When the build has succeeded, its `image` field holds the name of the new image. Pass that name to a sandbox. This
image runs a web server on port 8000, so the sandbox is reported as ready **once the app answers**, and the
sandbox's address then serves the API:

```bash title="curl" run capture=IMAGE=.image theme={null}
curl -sS "$FIBRE_API_URL/v1/builds/$BUILD" -H "Authorization: Bearer $FIBRE_API_KEY"
```

```typescript title="TypeScript" run theme={null}
const api = await Sandbox.create({ image: build.image!, exposedPort: 8000, lifetime: 600, labels: { docs: "images" } });
console.log(await fetch(api.url).then((r) => r.json())); // { message: 'built and served on Fibre' }
await api.delete();
```

```python title="Python" run theme={null}
import json
from urllib.request import urlopen

api = Sandbox.create(image=build["image"], exposed_port=8000, lifetime=600, labels={"docs": "images"})
print(json.load(urlopen(api.url)))  # {'message': 'built and served on Fibre'}
api.delete()
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "id": "…",
>   "status": "succeeded",
>   "image": "…",
>   "dockerfile": "Dockerfile",
>   "target": null,
>   "size_bytes": "…",
>   "cached": "…",
>   "builder": "…",
>   "builder_reason": "…",
>   "error": null,
>   "created_at": "…",
>   "started_at": "…",
>   "finished_at": "…"
> }
> ```

```bash title="curl: start it and call it" run theme={null}
SBX=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d "{\"image\": \"$IMAGE\", \"exposed_port\": 8000, \"lifetime_sec\": 600, \"labels\": {\"docs\": \"images\"}}" | jq -r .id)
URL=$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .url)
curl -sS "$URL/"
curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> built and served on Fibre
> ```

### Build options

You can adjust a build with these query parameters on `POST /v1/builds`:

| Parameter | Default | |
| - | - | - |
| `dockerfile` | `Dockerfile` | Its path inside the context |
| `target` | the last stage | Build up to a named stage of a multi-stage Dockerfile |
| `build_arg` | | `KEY=VALUE`, repeated for each argument (up to 64) |
| `no_cache` | `false` | `true` builds again even if an identical build exists |

While it runs and after it ends, a build has one of these statuses:

| Build `status` | Means |
| - | - |
| `building` | Running |
| `succeeded` | Done: `image` is set |
| `failed` | `error` says why; the log has the details |
| `canceled` | Stopped with `DELETE /v1/builds/{id}` |

> [!TIP]
>
> **Order the steps of your Dockerfile from the least to the most often changed**: system packages first, then
> dependencies, then your own code. Fibre reuses every step that has not changed, so if you only change `main.py`,
> only the last step is rebuilt.

A build runs in a sandbox of its own and is billed like one while it runs. The build context can be up to 2 GB.

## Image or snapshot?

Both images and snapshots give new sandboxes a head start, so it is worth knowing which to use. The difference is
**memory**: an image keeps only files, while a snapshot also keeps running programs and everything in memory.

| | Image | [Snapshot](https://docs.fibre.dev/setup/snapshots.md) |
| - | - | - |
| Keeps files and installed packages | ✓ | ✓ |
| Keeps running programs and memory | | ✓ |
| A new sandbox starts | Fresh: its own command runs from the start | Exactly where the source was |
| Made from | A registry, or a Dockerfile built on Fibre | A running sandbox |
| Best for | Toolchains, app images, reproducible environments | Warm servers, preloaded data, instant workspaces |

## Errors

| Status | Code | When |
| - | - | - |
| 403 | `image_not_owned` | The image belongs to another account |
| 404 | `image_not_found` | The image does not exist in its registry |
| 413 | `payload_too_large` | The build context is over 2 GB |

## Clean up

```bash title="Terminal" run theme={null}
rm -rf hello-api
```

```typescript title="TypeScript" run theme={null}
rmSync("hello-api", { recursive: true, force: true });
```

```python title="Python" run theme={null}
import shutil

shutil.rmtree("hello-api", ignore_errors=True)
```

## Related

> [card] [Snapshots](https://docs.fibre.dev/setup/snapshots.md)
>
> Save a sandbox's whole state and start new sandboxes from it, programs already running.

> [card] [Private registries](https://docs.fibre.dev/setup/registries.md)
>
> Run images from your own registry.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.