How to Use Multi-Stage Docker Builds for Rust

Use a multi-stage Dockerfile to compile Rust in a builder stage and copy the binary to a minimal final stage for smaller images.

Use a multi-stage Dockerfile with a builder stage to compile your Rust binary and a final stage to copy only the binary, excluding the toolchain and dependencies.

FROM rust:1.80-bookworm AS builder
WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:bookworm-slim
COPY --from=builder /app/target/release/my_binary /usr/local/bin/
CMD ["my_binary"]

Replace my_binary with the name of your binary found in target/release/ after running cargo build --release.