> ## Documentation index
> Fetch the complete documentation index at: https://upstash.com/docs/llms.txt
> Ask it with GET https://upstash.com/docs/ask?q=<keywords or question>. Short keywords rank best.
> Use these to discover all available pages before exploring further.
> Feature requests: https://upstash.com/docs/common/help/feature-requests.md lists what users asked for and how to vote for a request or add one.
> Page rating: `GET https://upstash.com/docs/feedback?path=/docs/box/guides/snapshot-base-image&helpful={true|false}&comment={comment}` records whether this page helped. The `comment` (URL-encoded, at most 500 characters) says what helped, or what was missing or wrong; a `helpful=false` rating needs it. It is anonymous and needs no key. Comments hold no code, secrets or personal data.

# Use a Snapshot as a Custom Base Image

> Set up an Upstash Box once, snapshot it, and start every new box from that snapshot in code. The snapshot works as a reusable template for new boxes.

Set up a box once, take a [snapshot](/box/overall/snapshots), and start every new box from it in code. System packages, dependencies, repos and files are already there when the box starts.

---

## 1. Build the image

Get a Box API key from the [Upstash Console](https://console.upstash.com/box).

```bash
export UPSTASH_BOX_API_KEY=box_xxxxxxxxxxxxxxxxxxxxxxxx
```

Create a box, install what you need, and snapshot it:

<CodeGroup>
```typescript build.ts
import { Box } from "@upstash/box"

const base = await Box.create({ runtime: "python" })

const setup = [
  "sudo apt-get update && sudo apt-get install -y ffmpeg",
  "pip install pandas duckdb",
]

for (const command of setup) {
  const run = await base.exec.command(command)
  if (run.exitCode !== 0) throw new Error(`${command}\n${run.result}`)
}

const snapshot = await base.snapshot({ name: "analyst-v1" })
await base.delete()

console.log(snapshot.id)
```

```python build.py
from upstash_box import Box

base = Box.create(runtime="python")

setup = [
    "sudo apt-get update && sudo apt-get install -y ffmpeg",
    "pip install pandas duckdb",
]

for command in setup:
    run = base.exec.command(command)
    if run.exit_code != 0:
        raise RuntimeError(f"{command}\n{run.result}")

snapshot = base.snapshot(name="analyst-v1")
base.delete()

print(snapshot.id)
```
</CodeGroup>

Save the printed ID:

```bash
export SNAPSHOT_ID=3f9c2a1e-7b4d-4c8e-9a51-2d6f0b8e4c17
```

A failed command does not throw, so the script checks each exit code before it snapshots. The snapshot does not depend on the box it came from, so the base box can be deleted.

### Set it up by hand instead

The setup does not have to be code. Create a box in the console, connect [over SSH](/box/overall/shell#ssh), and prepare it like any Linux machine. You can also ask the box's [agent](/box/overall/agent) to do it. When the box looks right, snapshot it by ID:

<CodeGroup>
```typescript snapshot.ts
import { Box } from "@upstash/box"

const base = await Box.get("current-wasp-05510")
const snapshot = await base.snapshot({ name: "analyst-v1" })

console.log(snapshot.id)
```

```python snapshot.py
from upstash_box import Box

base = Box.get("current-wasp-05510")
snapshot = base.snapshot(name="analyst-v1")

print(snapshot.id)
```
</CodeGroup>

---

## 2. Start boxes from it

Each job gets its own box with everything already installed.

<CodeGroup>
```typescript app.ts
import { Box } from "@upstash/box"

const snapshotId = process.env.SNAPSHOT_ID!

export async function runJob(jobId: string, script: string) {
  const box = await Box.fromSnapshot(snapshotId, { name: `job-${jobId}` })

  try {
    await box.files.write({ path: "job.py", content: script })
    const run = await box.exec.command("python job.py")
    return run.result
  } finally {
    await box.delete()
  }
}
```

```python app.py
import os
from upstash_box import Box

snapshot_id = os.environ["SNAPSHOT_ID"]

def run_job(job_id: str, script: str) -> str:
    box = Box.from_snapshot(snapshot_id, name=f"job-{job_id}")

    try:
        box.files.write(path="job.py", content=script)
        run = box.exec.command("python job.py")
        return run.result
    finally:
        box.delete()
```
</CodeGroup>

---

## 3. Pass settings on restore

A snapshot holds the disk, the env vars, and the runtime, agent model and browser setting. Everything else is set per box, so pass it to `fromSnapshot()`:

<CodeGroup>
```typescript app.ts
const box = await Box.fromSnapshot(snapshotId, {
  size: "medium",
  initCommand: "nohup python -m http.server 8000 > server.log 2>&1 &",
  networkPolicy: { mode: "custom", allowedDomains: ["api.github.com"] },
})
```

```python app.py
box = Box.from_snapshot(
    snapshot_id,
    size="medium",
    init_command="nohup python -m http.server 8000 > server.log 2>&1 &",
    network_policy={"mode": "custom", "allowed_domains": ["api.github.com"]},
)
```
</CodeGroup>

Running processes are not part of a snapshot. Start servers and databases with `initCommand`, which runs each time the box starts.

---

## 4. Update the image

Restore the current version, change it, and snapshot again:

<CodeGroup>
```typescript update.ts
import { Box } from "@upstash/box"

const base = await Box.fromSnapshot(process.env.SNAPSHOT_ID!)
const run = await base.exec.command("pip install matplotlib")
if (run.exitCode !== 0) throw new Error(run.result)

const snapshot = await base.snapshot({ name: "analyst-v2" })
await base.delete()

console.log(snapshot.id)
```

```python update.py
import os
from upstash_box import Box

base = Box.from_snapshot(os.environ["SNAPSHOT_ID"])
run = base.exec.command("pip install matplotlib")
if run.exit_code != 0:
    raise RuntimeError(run.result)

snapshot = base.snapshot(name="analyst-v2")
base.delete()

print(snapshot.id)
```
</CodeGroup>

Point `SNAPSHOT_ID` at the new ID to roll forward, and back at the old one to roll back. Boxes that are already running keep the version they started from.

---

## Troubleshooting

- **`apt-get` or `npm install -g` fails with a permission error**: a box runs as the non-root `boxuser`. Use `sudo` for system-wide installs.
- **The server is not running in a restored box**: processes do not survive a snapshot. Pass `initCommand` on restore.
- **The network policy is gone after restore**: it is not inherited. Pass `networkPolicy` again.
- **The agent uses a different API key**: a key passed as `apiKey` is not stored in the snapshot. Pass `agent` again on restore.
