Build static binaries for Alpine using cargo-chef
mainTo run your application in an alpine distribution, you must build a fully static binary (e.g., for x86_64-unknown-linux-musl). When cross-compiling, you must explicitly specify the --target flag in both cargo chef cook and cargo build.
# Using muslrust as base
FROM clux/muslrust:stable AS chef
USER root
RUN cargo install --locked cargo-chef
WORKDIR /app
FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
# Specify the target for cooking
RUN cargo chef cook --release --target x86_64-unknown-linux-musl --recipe-path recipe.json
COPY . .
# Specify the target for building
RUN cargo build --release --target x86_64-unknown-linux-musl --bin app
FROM alpine AS runtime
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/app /usr/local/bin/
CMD ["/usr/local/bin/app"]