Building Rust in Docker: Utilize Build Cache Properly!

From lucretiel‘s Tweet, which lead to one of his project’s Dockerfile… When building Rust in Docker, to cache the build, we can just add empty main.rs file, then run cargo build to build the dependencies first. Because the layer is cached, the built dependencies also cached too!

After that, we can just import the rest of the projects, then we can run the build as usual. See following snippets:

FROM rust:1.45-slim as web
WORKDIR /bobbin-web

# First, copy and build just our dependencies, with a dummy main. This way,
# future builds will reuse these dependencies.
COPY ./web/Cargo.toml .
COPY ./web/Cargo.lock .

RUN ["mkdir", "src/"]
RUN echo 'fn main() {panic!("if you see this, the build broke")}' > src/main.rs
RUN ["cargo", "build", "--release"]

# Now that dependencies are built, rebuild with the actual source. The previous
# steps will be skipped if Cargo.toml and Cargo.lock didn't chage (which means
# our compiled dependencies will be reused)
RUN rm target/*/deps/bobbin-*
COPY ./web .
RUN ["cargo", "build", "--release"]

Disclaimer:

Not all articles here are meant to be correct. My notes might be wrong or may no longer be relevant. If you want to try things here, please proceed with caution.


Posted

in

,

by

Tags: