Build a static musl binary into a scratch image

The runtime image contains only the binary and an empty hooks directory, and runs as an unprivileged numeric user. Hook scripts need a shell, so they will not run in this image.
This commit is contained in:
ktims committed 2026-10-22 17:49:12 -07:00
1 parent 8321d01ffb
commit ac154066e1
1 file changed
+12 -7
+12 -7
View File
@@ -1,4 +1,7 @@
FROM rust:1.94-bookworm AS builder FROM rust:1.94-bookworm AS builder
# Statically linked musl build. Override for other architectures, e.g. --build-arg RUST_TARGET=aarch64-unknown-linux-musl
ARG RUST_TARGET=x86_64-unknown-linux-musl
RUN rustup target add ${RUST_TARGET}
WORKDIR /build WORKDIR /build
# Build dependencies against stub sources so this layer is only invalidated by Cargo.toml/Cargo.lock changes. # Build dependencies against stub sources so this layer is only invalidated by Cargo.toml/Cargo.lock changes.
@@ -6,18 +9,20 @@ COPY Cargo.toml Cargo.lock ./
RUN mkdir -p src/bin \ RUN mkdir -p src/bin \
&& touch src/lib.rs \ && touch src/lib.rs \
&& echo 'fn main() {}' > src/bin/rust-bfdd.rs \ && echo 'fn main() {}' > src/bin/rust-bfdd.rs \
&& cargo build --release --locked --bin rust-bfdd \ && cargo build --release --locked --target ${RUST_TARGET} --bin rust-bfdd \
&& rm -rf src && rm -rf src
COPY src ./src COPY src ./src
# COPY keeps the host mtimes, which may predate the stub build; force cargo to rebuild the crate itself. # COPY keeps the host mtimes, which may predate the stub build; force cargo to rebuild the crate itself.
RUN touch src/lib.rs src/bin/rust-bfdd.rs \ RUN touch src/lib.rs src/bin/rust-bfdd.rs \
&& cargo build --release --locked --bin rust-bfdd && cargo build --release --locked --target ${RUST_TARGET} --bin rust-bfdd \
&& mkdir -p /rootfs/etc/rust-bfd/hooks.d \
&& cp target/${RUST_TARGET}/release/rust-bfdd /rootfs/rust-bfdd
FROM debian:bookworm-slim FROM scratch
RUN useradd --system --no-create-home --shell /usr/sbin/nologin bfd \ COPY --from=builder /rootfs/etc /etc
&& mkdir -p /etc/rust-bfd/hooks.d COPY --from=builder /rootfs/rust-bfdd /usr/local/bin/rust-bfdd
COPY --from=builder /build/target/release/rust-bfdd /usr/local/bin/rust-bfdd # No /etc/passwd in scratch, so use a numeric unprivileged user
USER bfd USER 10001:10001
EXPOSE 3784/udp EXPOSE 3784/udp
ENTRYPOINT ["/usr/local/bin/rust-bfdd"] ENTRYPOINT ["/usr/local/bin/rust-bfdd"]