Docker for Rust
Use case
You need to build and run your Rust app in a container: CI/CD, deployment, or consistent environments. A multi-stage Dockerfile keeps the final image small: one stage builds the binary, another stage runs it with a minimal base.
In C#: Like multi-stage Dockerfiles for .NET: build in SDK image, run in runtime image. In Rust there is no separate runtime; you ship a single binary, so the run stage only needs a minimal OS (e.g. alpine or scratch).
Multi-stage build
Stage 1: Use a Rust image (e.g. rust:1-bookworm) to build the binary with cargo build --release. Copy the binary out of target/release/your_bin.
Stage 2: Use a minimal image (e.g. debian:bookworm-slim or alpine) and copy only the binary. Set CMD or ENTRYPOINT to run it.
# Build stage
FROM rust:1-bookworm AS builder
WORKDIR /app
COPY . .
RUN cargo build --release
# Run stage
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/your_bin /usr/local/bin/
CMD ["your_bin"]In C#: Similar to FROM mcr.microsoft.com/dotnet/sdk then FROM mcr.microsoft.com/dotnet/runtime; in Rust you only copy the binary.
Reducing image size
- Build with
--releaseso the binary is optimized and smaller. - Use
rust:1-alpinefor build andalpinefor run to get very small images (you may need to install build deps in the build stage). - Strip the binary:
RUN strip /app/target/release/your_binbefore copying (optional).
In C#: Like publishing a self-contained single file and using a minimal runtime image.
Caching dependencies
Copy only Cargo.toml and Cargo.lock (and optionally a dummy src/main.rs), run cargo build --release, then copy the rest of the source. So dependency compilation is cached when only your code changes. For a workspace, the exact steps depend on the layout.
In C#: Like copying .csproj first and dotnet restore before copying the rest.
Key takeaway
Use a multi-stage Dockerfile: build with a Rust image, copy the release binary into a minimal run image. Use --release and consider Alpine or slim bases to keep the image small. Cache the dependency layer by copying manifest files first.