Skip to main content

ImageBuilder

Struct ImageBuilder 

Source
pub struct ImageBuilder { /* private fields */ }
Expand description

Image builder - orchestrates the full build process

ImageBuilder provides a fluent API for configuring and executing container image builds using buildah as the backend.

§Build Process

  1. Parse Dockerfile (or use runtime template)
  2. Resolve target stages if specified
  3. Build each stage sequentially:
    • Create working container from base image
    • Execute each instruction
    • Commit intermediate stages for COPY –from
  4. Commit final image with tags
  5. Push to registry if configured
  6. Clean up intermediate containers

§Cache Backend Integration (requires cache feature)

When a cache backend is configured, the builder can store and retrieve cached layer data to speed up subsequent builds:

use zlayer_builder::ImageBuilder;

let builder = ImageBuilder::new("./my-app").await?
    .with_cache_dir("/var/cache/zlayer")
    .tag("myapp:latest");

Implementations§

Source§

impl ImageBuilder

Source

pub async fn new(context: impl AsRef<Path>) -> Result<Self>

Create a new ImageBuilder with the given context directory

The context directory should contain the Dockerfile (unless using a runtime template) and any files that will be copied into the image.

§Arguments
  • context - Path to the build context directory
§Errors

Returns an error if:

  • The context directory does not exist
  • Buildah is not installed or not accessible
§Example
use zlayer_builder::ImageBuilder;

let builder = ImageBuilder::new("./my-project").await?;
Source

pub fn with_executor( context: impl AsRef<Path>, executor: BuildahExecutor, ) -> Result<Self>

Create an ImageBuilder with a custom buildah executor

This is useful for testing or when you need to configure the executor with specific storage options.

Source

pub fn dockerfile(self, path: impl AsRef<Path>) -> Self

Set a custom Dockerfile path

By default, the builder looks for a file named Dockerfile in the context directory. Use this method to specify a different path.

§Example
let builder = ImageBuilder::new("./my-project").await?
    .dockerfile("./my-project/Dockerfile.prod");
Source

pub fn zimagefile(self, path: impl AsRef<Path>) -> Self

Set a custom ZImagefile path

ZImagefiles are a YAML-based alternative to Dockerfiles. When set, the builder will parse the ZImagefile and convert it to the internal Dockerfile IR for execution.

§Example
let builder = ImageBuilder::new("./my-project").await?
    .zimagefile("./my-project/ZImagefile");
Source

pub fn runtime(self, runtime: Runtime) -> Self

Use a runtime template instead of a Dockerfile

Runtime templates provide pre-built Dockerfiles for common development environments. When set, the Dockerfile option is ignored.

§Example
use zlayer_builder::{ImageBuilder, Runtime};

let builder = ImageBuilder::new("./my-node-app").await?
    .runtime(Runtime::Node20);
Source

pub fn build_arg(self, key: impl Into<String>, value: impl Into<String>) -> Self

Add a build argument

Build arguments are passed to the Dockerfile and can be referenced using the ARG instruction.

§Example
let builder = ImageBuilder::new("./my-project").await?
    .build_arg("VERSION", "1.0.0")
    .build_arg("DEBUG", "false");
Source

pub fn build_args(self, args: HashMap<String, String>) -> Self

Set multiple build arguments at once

Source

pub fn target(self, stage: impl Into<String>) -> Self

Set the target stage for multi-stage builds

When building a multi-stage Dockerfile, you can stop at a specific stage instead of building all stages.

§Example
// Dockerfile:
// FROM node:20 AS builder
// ...
// FROM node:20-slim AS runtime
// ...

let builder = ImageBuilder::new("./my-project").await?
    .target("builder")
    .tag("myapp:builder");
Source

pub fn tag(self, tag: impl Into<String>) -> Self

Add an image tag

Tags are applied to the final image. You can add multiple tags. The first tag is used as the primary image name during commit.

§Example
let builder = ImageBuilder::new("./my-project").await?
    .tag("myapp:latest")
    .tag("myapp:v1.0.0")
    .tag("registry.example.com/myapp:v1.0.0");
Source

pub fn no_cache(self) -> Self

Disable layer caching

When enabled, all layers are rebuilt from scratch even if they could be served from cache.

Note: Currently this flag is tracked but not fully implemented in the build process. ZLayer uses manual container creation (buildah from, buildah run, buildah commit) which doesn’t have built-in caching like buildah build does. Future work could implement layer-level caching by checking instruction hashes against previously built layers.

Source

pub fn layers(self, enable: bool) -> Self

Enable or disable layer caching

This controls the --layers flag for buildah. When enabled (default), buildah can cache and reuse intermediate layers.

Note: ZLayer currently uses manual container creation (buildah from, buildah run, buildah commit) rather than buildah build, so this flag is reserved for future use when/if we switch to buildah build.

§Example
let builder = ImageBuilder::new("./my-project").await?
    .layers(false)  // Disable layer caching
    .tag("myapp:latest");
Source

pub fn cache_from(self, registry: impl Into<String>) -> Self

Set registry to pull cache from

This corresponds to buildah’s --cache-from flag, which allows pulling cached layers from a remote registry to speed up builds.

Note: ZLayer currently uses manual container creation (buildah from, buildah run, buildah commit) rather than buildah build, so this option is reserved for future implementation.

TODO: Implement remote cache support. This would require either:

  1. Switching to buildah build command which supports –cache-from natively
  2. Implementing custom layer caching with registry pull for intermediate layers
§Example
let builder = ImageBuilder::new("./my-project").await?
    .cache_from("registry.example.com/myapp:cache")
    .tag("myapp:latest");
Source

pub fn cache_to(self, registry: impl Into<String>) -> Self

Set registry to push cache to

This corresponds to buildah’s --cache-to flag, which allows pushing cached layers to a remote registry for future builds to use.

Note: ZLayer currently uses manual container creation (buildah from, buildah run, buildah commit) rather than buildah build, so this option is reserved for future implementation.

TODO: Implement remote cache support. This would require either:

  1. Switching to buildah build command which supports –cache-to natively
  2. Implementing custom layer caching with registry push for intermediate layers
§Example
let builder = ImageBuilder::new("./my-project").await?
    .cache_to("registry.example.com/myapp:cache")
    .tag("myapp:latest");
Source

pub fn cache_ttl(self, ttl: Duration) -> Self

Set maximum cache age

This corresponds to buildah’s --cache-ttl flag, which sets the maximum age for cached layers before they are considered stale.

Note: ZLayer currently uses manual container creation (buildah from, buildah run, buildah commit) rather than buildah build, so this option is reserved for future implementation.

TODO: Implement cache TTL support. This would require either:

  1. Switching to buildah build command which supports –cache-ttl natively
  2. Implementing custom cache expiration logic for our layer caching system
§Example
let builder = ImageBuilder::new("./my-project").await?
    .cache_ttl(Duration::from_secs(3600 * 24))  // 24 hours
    .tag("myapp:latest");
Source

pub fn push(self, auth: RegistryAuth) -> Self

Push the image to a registry after building

§Arguments
  • auth - Registry authentication credentials
§Example
use zlayer_builder::{ImageBuilder, RegistryAuth};

let builder = ImageBuilder::new("./my-project").await?
    .tag("registry.example.com/myapp:v1.0.0")
    .push(RegistryAuth::new("user", "password"));
Source

pub fn push_without_auth(self) -> Self

Enable pushing without authentication

Use this for registries that don’t require authentication (e.g., local registries, insecure registries).

Source

pub fn default_registry(self, registry: impl Into<String>) -> Self

Set a default OCI/WASM-compatible registry to check for images.

When set, the builder will probe this registry for short image names before qualifying them to docker.io. For example, if set to "git.example.com:5000" and the ZImagefile uses base: "myapp:latest", the builder will check git.example.com:5000/myapp:latest first.

Source

pub fn squash(self) -> Self

Squash all layers into a single layer

This reduces image size but loses layer caching benefits.

Source

pub fn format(self, format: impl Into<String>) -> Self

Set the image format

Valid values are “oci” (default) or “docker”.

Source

pub fn default_cache_mounts(self, mounts: Vec<RunMount>) -> Self

Set default cache mounts to inject into all RUN instructions

Source

pub fn retries(self, retries: u32) -> Self

Set the number of retries for failed RUN steps

Source

pub fn with_events(self, tx: Sender<BuildEvent>) -> Self

Set an event sender for TUI progress updates

Events will be sent as the build progresses, allowing you to display a progress UI or log build status.

§Example
use zlayer_builder::{ImageBuilder, BuildEvent};
use std::sync::mpsc;

let (tx, rx) = mpsc::channel::<BuildEvent>();

let builder = ImageBuilder::new("./my-project").await?
    .tag("myapp:latest")
    .with_events(tx);
Source

pub async fn build(self) -> Result<BuiltImage>

Run the build

This executes the complete build process:

  1. Parse Dockerfile or load runtime template
  2. Build all required stages
  3. Commit and tag the final image
  4. Push to registry if configured
  5. Clean up intermediate containers
§Errors

Returns an error if:

  • Dockerfile parsing fails
  • A buildah command fails
  • Target stage is not found
  • Registry push fails

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more