So is there a secret to building #Rust docker containers? When I `cargo install` or `cargo build` inside a container I end up with an image of 2.5GB 😱

#cargo #docker #rustlang #build

Follow

@kevin try `cargo build --release`. You can also try building your app inside an alpine container with static linking to link against musl for even smaller binaries.

@fin_ger that's almost what I've been trying to do yesterday.

I'm using rustlang/rust:nightly as a build container and then copy the compiled binary into a alpine container but of course it doesn't run because it's not compiled properly.

I don't know how to configure the build properly and I couldn't find docs yesterday - probably because I don't know what I should search for :D "static linking" is something I'll look into now, thanks!

@kevin You have to use the alpine container for compiling. E.g. `apk add cargo` and then get your project into the alpine container and compile inside alpine. When you are statically linking you can just copy the binary to a scratch container and it will work. You can check whether statically linking succeeded with ldd. The Dockerfile would roughly look like this:

@kevin
```
FROM alpine:edge
RUN apk update && apk add rust cargo
WORKDIR /project
RUN cargo build --release --target x86_64-alpine-linux-musl

FROM scratch
COPY --from=0 /project/target/x86_64-alpine-linux-musl/release/your-binary .
ENTRYPOINT [ "/your-binary" ]
```

@fin_ger thanks! That's exactly what I was looking for. I somehow didn't think about "just" installing rust and cargo in an alpine container :D

@kevin Thank the alpine team for providing rust tools in their awesome distro! Without the alpine team musl support for rust would be light years away ;) And with this statically linking for rust...

@fin_ger I should really thank them :D Been using Alpine for all my docker stuff for the past years!

FYI, I ended up using this github.com/clux/muslrust to build the binary because I needed rust nightly for the rocket lib. Image size is now down to 5MB from 2.5GB! :D

Sign in to participate in the conversation
Mastodon

Server run by the main developers of the project 🐘 It is not focused on any particular niche interest - everyone is welcome as long as you follow our code of conduct!