# Working with images

https://virtx.sh/docs/tutorials/images/

Build images from recipes, pull and push them, and manage the server's registry.

Every sandbox boots from an image: the read-only filesystem it starts from.
This page shows how to get images onto a server and manage them there: build, tag, pull, push, copy them between servers, and prune unused ones.

## Building images

An image can be built from a recipe in code, or from a Dockerfile.

### From a recipe

A recipe is a base image plus the steps to run on it: `.run(command)`, `.env(key, value)`, and `.workdir(directory)`, chained in the order they run. In Rust, each is a `.step(...)`: `Step::run`, `Step::env` and `Step::workdir`.

**Python**

```python
recipe = (
    Recipe("alpine:latest")
    .run("apk add --no-cache jq")
    .env("LANG", "C.UTF-8")
    .workdir("/work")
)
digest = await client.build_image(recipe, "jq:latest").complete(print=True)
```

**Node.js**

```js
const recipe = new Recipe('alpine:latest')
  .run('apk add --no-cache jq')
  .env('LANG', 'C.UTF-8')
  .workdir('/work')
const digest = await client.buildImage(recipe, 'jq:latest').complete({ print: true })
```

**Rust**

```rust
let recipe = Recipe::new("alpine:latest")
    .step(Step::run("apk add --no-cache jq"))
    .step(Step::env("LANG", "C.UTF-8"))
    .step(Step::workdir("/work"));
let digest = client.build_image(recipe, "jq:latest").complete(true).await?;
```

### From a Dockerfile

VirtX reads a Dockerfile as a recipe, so it supports a subset of Dockerfile syntax: a single stage with only `FROM`, `RUN`, `ENV` (in the `ENV key=value` form) and `WORKDIR`, and no `AS` stage name. Any other instruction fails with an error that names its line.

```dockerfile
FROM alpine:latest
RUN apk add --no-cache jq
ENV LANG=C.UTF-8
WORKDIR /work
```

The `virtx` command, which the Python and Node.js packages install, builds the Dockerfile in a directory, or the file that `-f` names. See [CLI](https://virtx.sh/docs/reference/cli/).

```sh
virtx build -t jq:latest .
```

In Rust, `Recipe::from_dockerfile` reads a Dockerfile's text into a recipe for `build_image`:

```rust
let recipe = Recipe::from_dockerfile(std::fs::read_to_string("Dockerfile")?)?;
let digest = client.build_image(recipe, "jq:latest").complete(true).await?;
```

### After a build

A build stores the image under the tag you gave. `create_sandbox` can boot it by that tag, or by its digest to use exactly that build.

The image keeps the steps it was built with in its history, which `docker history` shows once you push it. It names its base in the labels `org.opencontainers.image.base.name` and `org.opencontainers.image.base.digest`. A `RUN` step's command is kept as written, so don't put a secret in a step: pass it to the commands the sandbox runs instead.

Every command in the sandbox runs with the image's environment variables and working directory. If that directory isn't there, the sandbox makes it as its VM boots. If it can't, because a file is in its place or it is under a read-only volume, commands run in `/` and the VM's kernel log, which `dmesg` prints, says why. A `RUN` step in a build fails instead of running in `/`. VirtX doesn't run the image's entrypoint or command. To start a server the image contains, run it with `exec`.

A build, like a pull or a push, is a [job](https://virtx.sh/docs/tutorials/running-commands/#follow-a-job):

- `complete()` waits for the build to finish, prints its log if you pass `print`, and returns the digest of the new image. Always complete a build before you boot from its tag.
- If the build fails, `complete()` raises a `VirtxError` whose `source` is `job` (in Rust, a `virtx::Error` whose `source_kind()` is `Source::Job`).
- If you iterate the build instead, it yields the log and raises the same error in place of the `end` entry.
- If you await it, you get the job, and can read its log again later with `job.log()` (`job.log(None)` in Rust).

## Tagging

A tag is a `name:tag` that points at an image.

- `tag_image` points a new tag at an image, given by a tag or by `name@algorithm:hex`. If the new tag already points at another image, it moves.
- `untag_image` removes a tag and keeps the image.
- `list_image` lists every tag and the digest it points at.
- `remove_image` removes the image a reference names, and every tag on it under that name.

While a sandbox or a build uses an image, removing the image or its last tag fails with `409`, and no tags change.

**Python**

```python
await client.tag_image("jq:latest", "jq:1.7")
for item in await client.list_image():
    print(item.reference, item.digest)
await client.untag_image("jq:1.7")
```

**Node.js**

```js
await client.tagImage('jq:latest', 'jq:1.7')
for (const item of await client.listImage()) console.log(item.reference, item.digest)
await client.untagImage('jq:1.7')
```

**Rust**

```rust
client.tag_image("jq:latest", "jq:1.7").await?;
for item in client.list_image().await? {
    println!("{} {}", item.reference, item.digest);
}
client.untag_image("jq:1.7").await?;
```

An untagged image stays on the server until it is [pruned](#prune-the-registry).

## Pull and push

You don't need to build an image to start. `pull_image` copies an image from a registry, such as Docker Hub or `ghcr.io`, to the server, ready to boot. `push_image` copies an image to the registry in its name, so tag it with the registry's name first.

If the registry needs credentials, pass them as `auth`: a username with a password or access token, or a bearer token. Without `auth`, pulls and pushes are anonymous. These credentials are for the registry, not for the VirtX server.

**Python**

```python
import os

from virtx import BasicAuth

await client.pull_image("python:3.12-slim").complete(print=True)
sandbox = await client.create_sandbox("python:3.12-slim")

await client.tag_image("jq:latest", "ghcr.io/me/jq:1")
auth = BasicAuth("me", os.environ["GHCR_TOKEN"])
await client.push_image("ghcr.io/me/jq:1", auth).complete(print=True)
```

**Node.js**

```js
await client.pullImage('python:3.12-slim').complete({ print: true })
const sandbox = await client.createSandbox('python:3.12-slim')

await client.tagImage('jq:latest', 'ghcr.io/me/jq:1')
const auth = { type: 'basic', username: 'me', password: process.env.GHCR_TOKEN }
await client.pushImage('ghcr.io/me/jq:1', auth).complete({ print: true })
```

**Rust**

```rust
client.pull_image("python:3.12-slim", None).complete(true).await?;
let sandbox = client
    .create_sandbox(&SandboxCreateArgs::new("python:3.12-slim"))
    .await?;

client.tag_image("jq:latest", "ghcr.io/me/jq:1").await?;
let auth = RegistryAuth::Basic {
    username: "me".into(),
    password: std::env::var("GHCR_TOKEN")?,
};
client.push_image("ghcr.io/me/jq:1", Some(auth)).complete(true).await?;
```

### Registries on your own server

These settings apply to `virtx-server-tcp`. The local server reaches any registry your machine can reach.

- **Private registries:** `virtx-server-tcp` connects only to registries on public addresses, for pulls, pushes and build base images. A job that names a registry on the server's machine or private network fails with `is not reachable from this server`. To allow one, add it to `server.json` as `host` or `host:port`, exactly as image references name it: `"private_registries": ["registry.internal:5000"]`. If that registry redirects to another private host (for a token or a layer), list that host too.
- **Proxies:** registry connections don't use an `HTTPS_PROXY` set in the server's environment. A server that can reach the internet only through such a proxy can't reach any registry.
- **Docker Hub mirror:** Docker Hub limits anonymous pulls per address, and a server that pulls for many users reaches that limit quickly. Set a mirror in `server.json`, for example `"registry_mirror": "mirror.gcr.io"`. Anonymous pulls of Docker Hub images, including build base images, then try the mirror first and fall back to Docker Hub. The image is tagged with the name the job asked for either way. A tag on the mirror can lag behind Docker Hub, but a digest names the same image on both. Pulls with credentials always go to Docker Hub. A mirror on a private address must also be in `private_registries`.
- **Shared pulls:** with `"share_public_images": true`, projects on the server reuse each other's anonymous pulls. Read [Share public images](https://virtx.sh/docs/tutorials/self-hosting/#share-public-images) before you turn it on: it lets one project learn what another has pulled.

## Copy a local image to a remote server

You can move an image you built locally to a remote server without a registry. `download_image` writes the image from the local server to an OCI archive file. `upload_image` sends the archive to the remote server and tags it there, uploading only the layers that server doesn't have yet.

**Python**

```python
from virtx import Client, CommandAuth

async with Client.spawn() as local:
    async for _ in local.download_image("jq:latest", "jq.tar"):
        pass

async with Client.connect(
    "https://virtx.example", CommandAuth("uvx", ("virtx", "token", "--json"))
) as remote:
    async for _ in remote.upload_image("jq.tar", "jq:latest"):
        pass
    sandbox = await remote.create_sandbox("jq:latest")
```

**Node.js**

```js
const local = Client.spawn()
for await (const _ of local.downloadImage('jq:latest', 'jq.tar')) {}
await local.close()

const remote = Client.connect(
  'https://virtx.example',
  { type: 'command', program: 'npx', args: ['-y', '@brekkylab/virtx', 'token', '--json'] }
)
for await (const _ of remote.uploadImage('jq.tar', 'jq:latest')) {}
const sandbox = await remote.createSandbox('jq:latest')
```

**Rust**

```rust
use futures::StreamExt; // cargo add futures

let local = Client::spawn_virtx([] as [&str; 0]).await?;
let mut events = local.download_image("jq:latest", "jq.tar");
while let Some(event) = events.next().await {
    event?;
}

let remote = Client::connect(
    "https://virtx.example",
    Auth::Command { program: "uvx".into(), args: vec!["virtx".into(), "token".into(), "--json".into()] },
    None,
)?;
let mut events = remote.upload_image("jq.tar", "jq:latest");
while let Some(event) = events.next().await {
    event?;
}
let sandbox = remote
    .create_sandbox(&SandboxCreateArgs::new("jq:latest"))
    .await?;
```

The archive uses the standard OCI image layout, so other tools that support that layout can read or create it.

## Prune the registry

Rebuilding or untagging a tag leaves the old image on the server. `prune_image` deletes every image that no tag points at and no sandbox uses, along with the layers only those images used. It returns the deleted images and the number of bytes freed. Images less than an hour old are kept, so an image a build or upload just wrote isn't deleted before it is tagged.

**Python**

```python
pruned = await client.prune_image()
print(len(pruned.images), "images,", pruned.reclaimed, "bytes")
```

**Node.js**

```js
const pruned = await client.pruneImage()
console.log(pruned.images.length, 'images,', pruned.reclaimed, 'bytes')
```

**Rust**

```rust
let pruned = client.prune_image().await?;
println!("{} images, {} bytes", pruned.images.len(), pruned.reclaimed);
```

From a shell, `virtx image prune` does the same. `virtx-server-tcp` also prunes automatically once an hour. The local server prunes only when you ask it to.

## Troubleshooting

1. **`404`, `not_found`, `no image here is tagged …: pull it first`, from `create_sandbox`**

   **Cause:** The server has no image by that tag. A create does not pull.

   **Fix:** Pull or build the image, and `complete` the job, first.

2. **`… is not reachable from this server: it is not a public address`**

   **Cause:** A `virtx-server-tcp` job named a registry on the server's machine or private network.

   **Fix:** List the registry in `private_registries` in `server.json`.

3. **`409`, `DENIED in use: a sandbox or a build stands on …`**

   **Cause:** The image, or its last tag, is used by a sandbox or a build.

   **Fix:** Remove the sandbox, or let the build finish, then try again.

4. **`Dockerfile:N: … is not one of FROM, RUN, ENV and WORKDIR`**

   **Cause:** The Dockerfile uses another instruction, such as `COPY`, `CMD` or `USER`.

   **Fix:** Drop it. Put files in with [Reading and writing files](https://virtx.sh/docs/tutorials/reading-writing-files/), and start programs with `exec`.

5. **`Dockerfile:N: ENV with a bare word …`**

   **Cause:** `ENV key value`, the old form.

   **Fix:** Write `ENV key=value`.

6. **`Dockerfile:N: a second FROM …`, or `a named stage …`**

   **Cause:** A multi-stage Dockerfile.

   **Fix:** Use one stage, with one `FROM` and no `AS`.

7. **`the job was removed before it ended`**

   **Cause:** The job was removed while `complete` was waiting for it.

   **Fix:** Start the build or pull again, and leave it until it ends.

## Next

- [Setting up sandboxes](https://virtx.sh/docs/tutorials/setting-sandboxes/): boot a sandbox from the image.
- [Mounting volumes](https://virtx.sh/docs/tutorials/mounting-volumes/): keep data apart from the image, for any sandbox to mount.
