Expand description
Build local images from folders, HTTP(S) contexts, or Git repositories.
Use the same Docker daemon for builds and Testcontainers. Remove all containers before you remove their image.
§testcontainers-build
Build local Docker images from folders, HTTP(S) contexts, or Git repositories. Use fluent requests and native Testcontainers containers.
§Run an example
Docker CLI with buildx and a running Linux container engine are required. Git
sources also need Git on PATH. Use the same daemon for Docker CLI and Testcontainers.
cargo run -p testcontainers-build --example local
cargo run -p testcontainers-build --example remote
cargo run -p testcontainers-build --example git-sourceThe examples build an image, start a container, wait for readiness, check files, and remove resources. They use a nested Dockerfile, build arguments, a target stage, and a timeout. The local example disables the layer cache. The remote example serves a filtered tar archive from a temporary HTTP container. The Git example builds a pinned commit and selects a checkout subdirectory.
The shared context is in examples/context. Set
TESTCONTAINERS_BUILD_HTTP_HOST when the builder needs another address to reach
the temporary HTTP server. Pass an archive URI after --example remote --, or a
repository, revision, and optional subdirectory after --example git-source --.
External inputs must follow the sample contract; adapt its checks for your service.
§Fluent API
Add this library, testcontainers = "0.28", and Tokio to your application.
Replace ./service with your Docker build context:
use testcontainers::runners::AsyncRunner;
use testcontainers_build::{FolderSource, ImageBuilder};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut image = ImageBuilder::default()
.with_source(FolderSource::new("./service"))
.with_build_argument("VERSION", "1.0")
.build()
.await?;
let result = async {
let container = image.container_request().start().await?;
// Use the container here. Add service checks with cleanup on error paths.
container.rm().await
}
.await;
// Attempt image cleanup even when the container operation failed.
let cleanup = image.remove().await;
result?;
cleanup?;
Ok(())
}Configuration methods consume and return the request. Use with_dockerfile,
with_build_argument, with_target, with_platform, with_no_cache, and
with_timeout to set individual options. with_options replaces all options.
Validation runs before source resolution. The default timeout is ten minutes
and includes the build. The direct ImageBuilder::build(&source, &options) API
accepts borrowed inputs.
Use RemoteUriSource::new(uri)? for HTTP(S), or
GitSource::new(GitRequest::new(repository).with_revision(commit)) for Git.
Add with_subdirectory to select a checkout folder. Use a full commit ID for
repeatable builds.
§Ownership and source behavior
Remove containers before their image, and call image.remove().await on success
and error paths. Drop does not remove images. Testcontainers can attempt a
registry pull if the local image is missing. See
examples/common/image.rs for full checks and cleanup.
Folder and Git contexts use Docker’s ignore rules. HTTP(S) contexts must be tar
archives or plain Dockerfiles. Docker downloads them from the builder’s network.
Filter archives before creation: Docker does not apply their .dockerignore.
ZIP is not supported. A plain remote Dockerfile has no local files for COPY.
The default Git provider does not explicitly initialize submodules or manage Git LFS. Use a custom provider for those steps. Dropping a process future requests termination; it does not guarantee all descendants stop.
§Extension points and layout
Implement BuildContextProvider to add a source, GitProvider to change checkout
behavior, or ImageBuildBackend to change image build execution.
BuildContext::with_owner holds temporary resources until the build ends.
The package uses Cargo’s src, tests, and examples conventions. Targets with
support modules use name/main.rs. It inherits the workspace’s Rust, Clippy,
and rustdoc lints. Check all targets with:
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo test --workspace
cargo doc --workspace --no-deps
cargo test --workspace --test docker -- --ignoredThe last command requires Docker. Repository integration tests use shared workspace fixtures and are not included in the package archive. The runnable examples and their context are included.
§License
This crate uses the MIT license.
Structs§
- Build
Context - Hold a build context and its optional resource owner. Release the owner when the context is dropped.
- Build
Options - Set the image build options. Use Default to set a ten-minute timeout.
- Built
Image - Hold the unique local image reference. Remove all containers before you call remove.
- Docker
CliBackend - Run image operations with the Docker CLI. Use the active Docker context and environment.
- Folder
Source - Use an existing folder as a build context. Do not copy or delete the folder.
- GitCli
Provider - Fetch one revision with the Git CLI. Keep the checkout in a temporary directory.
- GitRequest
- Select a Git repository and build subdirectory. Use a commit ID for repeatable builds.
- GitSource
- Resolve a Git request with a Git provider. Keep the provider separate from image build execution.
- Image
Build Request - Configure a build for a source with a fluent API. Configuration methods consume and return the request.
- Image
Builder - Resolve sources and build unique local images. Keep each context until its image build completes.
- Remote
UriSource - Use an HTTP(S) tar archive or plain Dockerfile. The Docker builder downloads the context.
Enums§
- Context
Location - Select a local folder or remote context. The image backend receives this location.
- Error
- Report source and image operation failures. Command errors include the tool output.
Traits§
- Build
Context Provider - Resolve a source before the image build starts. Return a context that owns any temporary resources.
- GitProvider
- Define how to check out a Git source. Replace this provider to change hosting or authentication.
- Image
Build Backend - Define image build and removal operations. Keep this implementation separate from source resolution.
Functions§
- validate_
relative - Validate a path relative to a build context. Use forward slashes and reject parent traversal.
Type Aliases§
- Result
- Return a value or a library error. Use the error to inspect operation failures.