A container build should produce the same application from a known source revision and dependency lockfile. Rust’s compile step can be expensive, so layer order and cache behavior affect developer feedback, but caching must not weaken reproducibility.
Separate dependency inputs from source changes
Copy
Cargo.tomlCargo.lockcargo build --lockedUse a builder image with the compiler and a runtime image containing only required libraries and the executable. Whether a minimal or distroless runtime works depends on the target’s libc and native dependencies. Verify the binary in the actual final image rather than assuming a successful builder stage proves runtime compatibility.
Preserve useful diagnostics
Build with explicit target and profile settings. Avoid copying secrets into build arguments or image layers. Pin base images according to the project’s update policy and rebuild regularly for security updates. Multi-platform builds require compatible target toolchains and should be tested on each published architecture.
Inspect image size, startup behavior, and graceful shutdown. Run the container as a non-root user where possible, give it only required filesystem access, and include a health check that reflects the service’s real readiness. A cache optimization is successful when it shortens repeated builds without hiding undeclared inputs.
Build dependencies and runtime requirements deliberately
Cargo's --locked makes a build fail when dependency resolution would change the lockfile. --offline prevents network access, and --frozen combines that with the lockfile requirement. A frozen build still needs dependencies available locally. Copy dependency manifests and fetch them in a build stage, then compile application source from the locked set. Cargo build reference
A multi-stage Dockerfile can copy the compiled binary into a smaller runtime stage and leave the compiler behind. Match runtime libraries to the binary's target, especially when switching between glibc and musl or when native dependencies are involved. Build for the target architecture, then launch the actual runtime image in a test environment. A compiler version check, like the example below, establishes only that the pinned toolchain image starts. Docker multi-stage builds
Worked example
This only verifies the pinned compiler image can start; the image must already be available locally. A real build needs a writable target directory and pre-fetched dependencies when networking is disabled.
shdocker run --rm --network none \ --mount type=bind,src="$PWD",dst=/work,readonly \ --workdir /work rust:1.85 cargo --version




Community
Discussion
Loading comments…