Run rust in Docker (musl compiled in a scratch image)

I spend a day on getting a smooth process for building small docker images with my rust app. I had some native c things in my dependencies (such as rdkafka). I found the process a little bit cumbersome but finally I found a well working solution that I hope can help someone else!

https://github.com/bjornmolin/rust-minimal-docker

5 Likes

Awesome thank you!
I like your docker ideas on building dependencies only when the cargo file changes.

Thank You! Actually I have learned that trick from other clever developers while I optimized some java and nodejs deploy pipelines, it is a very useful.

However, I miss a cargo command that just download and build dependencies. At least, I have not found one.

isn't it doing the other way around? i think docker is caching everything unless there is a change? so without adding the cargo.toml & .lock files it wouldn't update anything?

I think the little problem with docker and cargo is that in order to run cargo build I have to add src. When things change in src it invalidates the cached build. I would personally prefer a command in cargo that allow me to do something like this

COPY Cargo.lock .
COPY Cargo.toml .
cargo some-kind-of-download-and-build-dependencies-command
COPY src ./src
cargo build --target x86_64-unknown-linux-musl --release

Then docker will cache the dependencies until the Cargo.toml and Cargo.lock is modified. This is essentially what the work around with dummy main do.

1 Like

Ahh, ok, so you're adding a docker-layer only for the dependencies by building a dummy.

For node a simple RUN npm install would be enough to do that.

Exactly :slight_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.