Volumes give a sandbox direct filesystem access to host-side directories. They’re useful for persisting data across restarts, sharing data between sandboxes, or mounting host directories into the guest. They’re also significantly faster than the filesystem API (which transfers files individually), so for anything beyond ad-hoc reads and writes, volumes are the way to go.
microsandbox supports three types of mounts: bind mounts, named volumes, and tmpfs.
Bind mounts
Mount a directory from the host directly into the sandbox. Changes inside the sandbox are reflected on the host, and vice versa.
let sb = Sandbox::builder("dev")
.image("python:3.12")
.volume("/app/src", |v| v.bind("./src").readonly())
.volume("/app/data", |v| v.bind("./data"))
.create()
.await?;
Named volumes
Named volumes are managed by microsandbox and stored at ~/.microsandbox/volumes/<name>/. They persist independently of any sandbox, so you can create a volume, populate it, and mount it into different sandboxes over time.
Create a volume
let cache = Volume::builder("pip-cache")
.quota(1024)
.create()
.await?;
Mount in a sandbox
let sb = Sandbox::builder("worker")
.image("python:3.12")
.volume("/root/.cache/pip", |v| v.named(cache.name()))
.create()
.await?;
Share between sandboxes
Named volumes are the simplest way to share data between sandboxes. Mount the same volume into multiple sandboxes: one writes, another reads.
// Writer
let writer = Sandbox::builder("writer")
.image("alpine:latest")
.volume("/data", |v| v.named("shared-data"))
.create()
.await?;
writer.shell("echo 'hello' > /data/message.txt").await?;
// Reader (read-only)
let reader = Sandbox::builder("reader")
.image("alpine:latest")
.volume("/data", |v| v.named("shared-data").readonly())
.create()
.await?;
let output = reader.exec("cat", ["/data/message.txt"]).await?;
// => "hello"
When sharing volumes between sandboxes, both sandboxes access the same underlying host directory. There’s no built-in locking, so if two sandboxes write to the same file concurrently, you’ll get the usual race conditions. Use the read-only flag on the reader side to make intent explicit.
Host-side access
Named volumes are accessible from the host even without a running sandbox, which is handy for pre-populating data before any sandbox mounts it.
let vol = Volume::get("pip-cache").await?;
vol.fs().write("/requirements.txt", "requests==2.28.0").await?;
Manage volumes
let volumes = Volume::list().await?;
Volume::remove("old-cache").await?;
Tmpfs
An in-memory filesystem that disappears when the sandbox stops. Useful for scratch space, build artifacts, or anything that doesn’t need to outlive the sandbox.
let sb = Sandbox::builder("worker")
.image("alpine:latest")
.volume("/tmp/scratch", |v| v.tmpfs().size(100))
.create()
.await?;