emk / rust-musl-builder

Docker images for compiling static Rust binaries using musl-libc and musl-gcc, with static versions of useful C libraries. Supports openssl and diesel crates.
Apache License 2.0
1.54k stars 193 forks source link

Multistage build and docker layers cache #101

Closed iammichiel closed 4 years ago

iammichiel commented 4 years ago

What did you try to do?

HI there,

I am trying to build an actix app using your image. Everything works great if I go for a full build without any cache. However, when using docker layers cache for cargo dependencies, I must be missing something...

This is the working (extract) version from my Dockerfile :

FROM ekidd/rust-musl-builder:latest AS build
ENV SQLX_OFFLINE=1
WORKDIR /home/rust
COPY --chown=rust:rust ./ /home/rust/
RUN cargo build --release -v

And when trying to add a pinch of cache using docker layers,

FROM ekidd/rust-musl-builder:latest AS build
ENV SQLX_OFFLINE=1
WORKDIR /home/rust

RUN USER=rust cargo init
COPY Cargo.toml /home/rust/
COPY Cargo.lock /home/rust/
RUN cargo build --release

COPY --chown=rust:rust ./ /home/rust/
RUN cargo build --release -v

On the second run, cargo is not picking up any changes from the first run and thus produces the "Hello world" binary from the cargo init command. Not sure, what I am missing here... Any clues?

iammichiel commented 4 years ago

And after digging a little on the rust forum, Cargo uses the timestamp to determine if a binary needs to be compiled or not. This post in particular seems to describe the situation nicely.

You already compiled an application before removing it’s source files, then when adding yours into the container, main.rs is probably older than the already built artifact, therefore cargo considers it unnecessary to recompile.

Meh.

emk commented 4 years ago

For caching notes, please see the README, which should explain how to store build caches in Docker volumes when building using RUN cargo build.