Follow

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

Β· Web Β· 2 Β· 0 Β· 0

@kevin Cargo's cache for incremental compilation is HUGE. You may want to rm -rf it after you've got the build products you wanted. Or use Cargo's env vars to tell Cargo to store its stuff in some dir that isn't part of the image.

@kornel I figured as much, was shocked when I saw a 2.5GB container for literally a 1-file web server. :D

My problem was also that I want to use alpine linux but am not building for alpine yet because I've no idea how to configure my builds. Will need to do more research.

@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

bullgit.party is a instance for everyone who is part of bullgit. πŸŽ‰