Rust Dockerfile Generator: Complete Guide
Efficient Rust Docker Builds with Cargo Caching
Rust compile times are notoriously long. By creating a dummy project that only contains your Cargo.toml and Cargo.lock, you can pre-compile all dependencies in a cached Docker layer. When your source code changes, only your application code is recompiled.
# Stage 1: Builder
FROM rust:1.75 AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs && cargo build --release && rm -rf src
COPY src ./src
RUN cargo build --release
# Stage 2: Runner
FROM alpine:3.18
WORKDIR /app
COPY --from=builder /app/target/release/myapp ./app
EXPOSE 8080
CMD ["./app"]