Building executable for Alpine linux


#1

I’m building a Rust executable which has to run on an Alpine Linux distribution.

Unfortunately, the Linux build (which we run on Ubuntu) has:

$ ldd lodex 
    linux-vdso.so.1 =>  (0x00007ffff11a8000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f4a483a9000)
    librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f4a481a1000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f4a47f83000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f4a47d6c000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f4a479a5000)
    /lib64/ld-linux-x86-64.so.2 (0x0000558610a7e000)

and this fails to run on the (virtual) machine we want to deploy this to, which uses Alpine Linux.

How can I either build a Linux executable which doesn’t load anything else, or target the Alpine Linux distribution properly?

I have looked at the linkage section of the Rust manuals and it seems I cannot control the system libraries which are dynamically linked by this means.


#2

You can cross compile to the x86_64-unknown-linux-musl target:

$ rustup target add x86_64-unknown-linux-musl
$ cargo build --target x86_64-unknown-linux-musl

If your crate or its dependencies depend on C libraries, you may need to cross compile them with musl-gcc.


#3

I’ve installed the target on my Mac, but the targeted build fails because it cannot be linkedited (cc complains about the parameters it is given).

I guess I need a toolchain on my Mac to link for musl. This is tricky, so instead I’m going to build a targeted executable on our (Ubuntu) build machine. I need to extend the Rust currently installed there, and archive the (new) build from target/release/x86_64-unknown-linux-musl/ instead of target/release/.

Wish me luck.

PS: It is implies (elsewhere on the forum) that this will give me a statically linked binary that runs on any linux. Is this true?


#4

Yep, you’ll end up with a fully static binary.

Here’s an example of a musl build for reference: https://circleci.com/gh/sfackler/cargo-sls-distribution/52


#5

And I did end up with one. Brill. Thank you.