Skip to content

feat(wb): reuse published container images from committed build contexts under cf - #1697

Open
exKAZUu wants to merge 5 commits into
mainfrom
feat/cf-container-image-reuse
Open

exKAZUu wants to merge 5 commits into
mainfrom
feat/cf-container-image-reuse

Conversation

@exKAZUu

@exKAZUu exKAZUu commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Close #1685

Why

Under the cf CLI, cf build builds every Dockerfile container image itself from the working tree, and wb deploy --containers-rollout was only forwarded to cf deploy. So every deploy of a container-backed Worker ran a Docker build (even with --containers-rollout=none), uncommitted and untracked files reached the image, and an unchanged image was rebuilt and re-pushed. The wrangler-era wb avoided this by rewriting the wrangler JSON config, which is impossible with a cloudflare.config.ts.

How the references reach the build was settled from cf 1.0.0-rc.6 / @cloudflare/config 1.0.0-rc.4 and the Wrangler build it delegates to (4.168.0):

  • defineContainer() takes image (and each entry of a Durable Object-managed Container's images) as either { dockerfile, buildContext?, buildVars? } or { reference }. A { reference } passes through the build unchanged into .cloudflare/output/v1/containers/<name>/container.config.json; only Dockerfile images are built (localReference). A build whose images are all references runs without Docker on PATH.
  • cf build has no option to skip image builds, and the Build Output Specification documents localReference as an already-built local image; rewriting the output before cf deploy --prebuilt is not a supported contract.
  • A named image of a Durable Object-managed Container must be <managed registry>/<account-id>/<repository>@sha256:<64 hex>. cf's resolver keeps such an account-qualified reference, inserts the account into a managed-registry reference without one, and rejects one whose 32-hex account segment is another account's.
  • The cf docs state that cloudflare.config.ts may read environment variables.

So the config reads a variable wb exports, in place of the Dockerfile. Rewriting Build Output or keeping cf from building were the alternatives, and neither is a cf contract.

Requirements

  • required: Before the build, for each container image defined by a Dockerfile, wb derives the reuse key (Worker name, the context's Git tree, the relative Dockerfile path, the build variables, linux/amd64), looks the image up in Cloudflare's managed registry, and on a miss builds it from the committed tree and pushes it.
  • required: The build uses the resolved registry references instead of building the Dockerfile.
  • required: A context with uncommitted changes to tracked files aborts the deploy before any build.
  • required: An image is never built from uncommitted or untracked files.
  • required: An unchanged committed context whose image is published deploys with no docker build, and the deployed container references the published digest.
  • required: --containers-rollout=none and an omitted flag do no lookup, and deploy a container-backed Worker without Docker.
  • chosen: cloudflare.config.ts reads WB_CONTAINER_IMAGE_<NAME> as { reference } in place of { dockerfile }, one variable per image named after cf's repository name for it, because a plain variable is the smallest thing a config can read without wb rewriting it, and per-image names need no parsing in the config.
  • chosen: wb evaluates the config with the variables set and stops before the build when an image ignores its variable, because otherwise cf would silently build that Dockerfile from the working tree.
  • chosen: with none, or without the flag whenever the config has a container image, wb exports placeholder references and passes --containers-rollout=none to cf deploy, because without a lookup there is no real image, cf takes one strategy for every Container, and none makes cf upload no image (it keeps the deployed Container metadata, or none on a first deploy).
  • chosen: every resolved reference is digest-pinned, because cf accepts only that form for named images of Durable Object-managed Containers.
  • chosen: wb exports no variable for images declared only by { reference } and never builds them, because such images are built outside wb (e.g. a Dockerfile that needs a BuildKit secret).
  • chosen: a Dockerfile image's Dockerfile lies inside its build context, as in the wrangler-era implementation, because no WillBooster repository needs otherwise and the rule keeps the committed source one Git tree.
  • chosen: wb removes WB_CONTAINER_IMAGE_* from the environment the config is evaluated under, because an exported stale value would replace a Dockerfile image with an unrelated image.

Customer Summary

A project whose Worker builds a container image from a Dockerfile changes its cloudflare.config.ts once:

const appImage = process.env.WB_CONTAINER_IMAGE_RUNNER_APP;
const runner = defineContainer({
  name: 'runner',
  schedulingPolicy: 'durable-object',
  images: { app: appImage ? { reference: appImage } : { dockerfile: './runner/Dockerfile' } },
});

Then:

  • wb deploy --containers-rollout=gradual|immediate reuses the published image of an unchanged committed context with no Docker build, and otherwise builds it from the committed tree, pushes it, and deploys its digest. Uncommitted changes in the build context stop the deploy before anything is built.
  • wb deploy --containers-rollout=none, or wb deploy without the flag, deploys the Worker without Docker and without touching the deployed Containers, including those declared only by registry reference.
  • Local wb start and wb test are unchanged: without the variable, the config keeps the Dockerfile.

Technical Summary

  1. packages/wb/src/utils/containerImages.ts (new) first evaluates the config with placeholder references and stops when an image ignores its variable, before any lookup or build. It carries over the wrangler-era logic: the same reuse key and wb/<name>:source-<key> tag, the dirty-context check (now git status --porcelain --untracked-files=no -- <context>, so staged changes count too), git archive extraction, and docker build --load --provenance=false --platform linux/amd64. Under cf it gets pull credentials with cf containers registries credentials generate <registry> --permissions pull (the stdout carrying the password is captured, never printed), finds the digest with a HEAD on the manifest, and pushes with cf containers push --tag. All contexts are checked before the first build. The registry host is CLOUDFLARE_CONTAINER_REGISTRY when set, because cf pushes and validates against it.
  2. packages/wb/src/utils/cloudflareConfig.ts reads containers from the evaluated config into containerImages (named as cf names their repositories: the Container name, or <Container>-<image>).
  3. packages/wb/src/commands/deploy.ts resolves the references after secrets and limits are checked and before gen-code and the build, passes them only to the build, and passes the effective rollout to both cf deploy calls.
  4. --dry-run checks the contexts and prints the tag each would use, without registry access.

Check hardest: that none never uploads the placeholder. This rests on reading cf's deploy code (with none, it skips preparing images and sends only Container names and classes, taken from the deployed version or left without images on a first deploy), not on a real deploy.

Testing

  • bun run verify.
  • bun wb test test/unit/cloudflareContainerImages.test.ts test/unit/deploy.test.ts test/unit/cloudflareWorker.test.ts. The new tests run wb deploy with the real cf build on a Git fixture with a Durable Object-managed Container, against a loopback Cloudflare API (CLOUDFLARE_API_BASE_URL, answered by the real cf containers registries credentials generate) and a loopback HTTPS registry. Only docker, cf containers push, and cf deploy are stubs. They cover: a miss builds once from the committed tree (untracked file excluded) and the Build Output holds the published digest; the next deploy builds nothing; a committed change builds again; an uncommitted change stops before any build, lookup, or cf build; none and an omitted flag run no Docker build and no lookup and deploy with --containers-rollout=none; a config ignoring the variable stops before the build.
  • Manually: the docker build arguments wb uses produce a linux/amd64 image locally, which cf containers push requires. Real cf deploy --prebuilt --dry-run accepts placeholder references with none and gradual.
  • Not exercised: the real registry lookup against registry.cloudflare.com, a real push, and a real deploy (no Cloudflare resources were touched). To verify on a real project: change its cloudflare.config.ts as above, commit, and run WB_ENV=staging bun wb deploy --containers-rollout=gradual twice. The first run builds and pushes wb/<name>:source-<key>; the second prints Reusing the published container image with no docker build; .cloudflare/output/v1/containers/*/container.config.json holds a registry.cloudflare.com/<account>/wb/...@sha256: reference. Then run bun wb deploy --containers-rollout=none with Docker stopped and check in the dashboard that the Container image is unchanged.

Notes

  • Behavior change: without --containers-rollout, a Worker with any container image is now deployed with --containers-rollout=none instead of cf's default rollout, so its images, including ones declared only by { reference }, change only with gradual or immediate.
  • code-gauge reports that the test share of the repository exceeds its limit; the added tests guard that images are never built from uncommitted files and that a published image is reused.

…xts under cf

cloudflare.config.ts reads WB_CONTAINER_IMAGE_<NAME> in place of each
Dockerfile image. With --containers-rollout=gradual|immediate, wb sets it
to the digest-pinned reference of the image built from the committed
build context, reusing a published one or building it from git archive
and pushing it with cf containers push; a dirty context stops the deploy
before any build. With none, or without the flag, wb sets placeholders
and deploys with --containers-rollout=none, so the build needs no Docker.

Co-authored-by: WillBooster (Claude Code) <agent@willbooster.com>
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a robust system for managing container images in Cloudflare Workers via wb. By leveraging committed Git tree hashes and Cloudflare's managed registry, the system ensures that unchanged container images are reused across deployments, significantly reducing build times. It also enforces strict build context validation to maintain consistency and provides flexible rollout options for container-backed Workers.

Highlights

  • Container Image Reuse: Implemented a mechanism to reuse published container images from committed build contexts, preventing unnecessary Docker builds during deployment.
  • Configuration Integration: Updated cloudflare.config.ts to support dynamic image references via environment variables, allowing wb to inject digest-pinned references.
  • Deployment Safety: Added a check to abort deployments if the build context contains uncommitted changes, ensuring reproducibility and preventing untracked files from reaching the image.
  • Rollout Strategies: Enhanced wb deploy with granular control over container rollouts, supporting none, gradual, and immediate strategies.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.


The Docker build is slow and long, But now our images are strong. With digest pins and committed tree, We deploy with speed and certainty.

Footnotes

  1. Review the Generative AI Prohibited Use Policy, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@exKAZUu

exKAZUu commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

ReviewFixLoop run dcc063e8be88-2 started: https://reviewfixloop.com/runs/dcc063e8be88-2

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces robust handling for Cloudflare Container images built from Dockerfiles during deployment. It adds functionality to resolve, build, and publish container images based on the committed Git tree, preventing uncommitted or untracked files from reaching the image, and reusing already published images to avoid redundant Docker builds. It also updates the documentation and adds comprehensive unit tests. Feedback was provided to improve the robustness of parseJsonObject in containerImages.ts by scanning for the JSON credentials block from the end of stdout instead of the beginning, preventing potential parsing failures if preceding configuration steps output JSON.

Comment on lines +233 to +242
function parseJsonObject(stdout: string): unknown {
for (const { index } of stdout.matchAll(/\{/gu)) {
try {
return JSON.parse(stdout.slice(index));
} catch {
// Not the start of the result.
}
}
throw new Error('cf printed no registry credentials.');
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since cf evaluates the config before printing the credentials, any JSON printed by the config to stdout would appear before the actual credentials JSON. Currently, parseJsonObject scans from the beginning of stdout and returns the first successfully parsed JSON, which could be an unrelated JSON printed by the config, causing schema validation to fail. Scanning from the end of stdout (by reversing the matches) is more robust as the command's output is always the last printed JSON.

function parseJsonObject(stdout: string): unknown {
  const matches = Array.from(stdout.matchAll(/\{/gu));
  for (let i = matches.length - 1; i >= 0; i--) {
    const index = matches[i].index;
    try {
      return JSON.parse(stdout.slice(index));
    } catch {
      // Not the start of the result.
    }
  }
  throw new Error('cf printed no registry credentials.');
}

exKAZUu and others added 4 commits November 26, 2026 21:52
…push

Co-authored-by: WillBooster (Claude Code) <agent@willbooster.com>
…tted

Co-authored-by: WillBooster (Claude Code) <agent@willbooster.com>
…out flag is omitted

Co-authored-by: WillBooster (Claude Code) <agent@willbooster.com>
…s did

Co-authored-by: WillBooster (Claude Code) <agent@willbooster.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(wb): reuse published container images from committed build contexts under cf

1 participant