From a47cee6e2f0f1267668ab74cbe0183ccfb1245ad Mon Sep 17 00:00:00 2001 From: Oleksiy Pyltsov Date: Wed, 26 Aug 2026 16:32:20 +0200 Subject: [PATCH] Use cargo-chef so the Docker layer cache works cache-to: type=gha exports image layers only: the contents of RUN cache mounts (cargo registry, target/) live inside the buildx builder, which CI recreates on every run. The COPY . . layer changes with every commit, so the cargo build layer never hits and each push compiles all dependencies from scratch (~10 min). cargo-chef moves dependency compilation into a layer keyed only by recipe.json, derived from Cargo.toml/Cargo.lock. That layer survives source-only commits, so a typical build recompiles just this crate. --- Dockerfile | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index f7a3822..1e63da8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,14 +1,20 @@ # syntax=docker/dockerfile:1.24 # check=error=true -FROM rust:1.96-slim-trixie AS build +FROM lukemathwalker/cargo-chef:0.1.77-rust-1.96-slim-trixie AS chef WORKDIR /app + +FROM chef AS planner +COPY --exclude=target --exclude=.git . . +RUN cargo chef prepare --recipe-path recipe.json + +FROM chef AS build +COPY --from=planner /app/recipe.json recipe.json +# Dependencies are compiled into their own layer, cached until recipe.json changes +RUN cargo chef cook --release --recipe-path recipe.json COPY --exclude=target --exclude=.git . . -RUN --mount=type=cache,target=/usr/local/cargo/registry \ - --mount=type=cache,target=/app/target \ - cargo build --release && \ - cp target/release/rust-template /rust-template +RUN cargo build --release FROM gcr.io/distroless/cc-debian13:nonroot -COPY --link --from=build /rust-template / +COPY --link --from=build /app/target/release/rust-template / ENTRYPOINT ["/rust-template"]