Snapshot and Restore Your Container Filesystem on Cloudflare Containers!
Hi, it's Shii-chan! A feature for saving a container's contents has arrived, so let's take a look!
Cloudflare ChangelogWhat was announced?
The Cloudflare Changelog announced that snapshot APIs for Containers are now in public beta. They let you save a point-in-time filesystem state and restore it later.
The story so far
The announcement doesn't describe how restoring files after a sleep or restart worked before. Think of the snapshot APIs as a dedicated way to do it.
What changes
With a snapshot, you can restore files after a Container sleeps, restarts, or is handed off to another Durable Object. That's handy for apps that need to carry work-in-progress state forward.
Dive Deep
It takes two steps. First, use snapshotContainer() from the Durable Object Container API to capture the full container filesystem. Store the handle, then pass it to start() when you want to restore.
import { DurableObject } from "cloudflare:workers";
export class MyDurableObject extends DurableObject {
async saveSnapshot() {
// Create a snapshot from the running Container.
const containerSnapshot = await this.ctx.container.snapshotContainer({});
await this.ctx.storage.put("containerSnapshot", containerSnapshot);
}
async restoreSnapshot() {
// Restore the saved snapshot later.
const containerSnapshot = await this.ctx.storage.get("containerSnapshot");
if (!containerSnapshot) {
return;
}
this.ctx.container.start({ containerSnapshot, enableInternet: false });
}
}
Two things to keep in mind:
- Snapshots require the
durable_objectscheduling policy - Snapshots are immutable, so create a new snapshot to persist filesystem changes made after a restore
See the Snapshots guide and the Durable Object Container API documentation for more.
Wrap-up
- Snapshot APIs for Containers are in public beta
- Capture the whole filesystem with
snapshotContainer()and restore by passing it tostart() - Works across sleep, restart, and handoff to another Durable Object
- Requires the
durable_objectscheduling policy, and snapshots are immutable
This is a great fit if you use Cloudflare Containers and want to carry working state forward!