The perfect Rust Dockerfile for CI/CD
Speed up your Rust container build and reduce CI/CD costs to the minimum by caching as much as possible with this perfect Dockerfile.
For my current backend project, written in Rust with actix-web and SQLx, I was looking for a proper CI/CD template, but couldn't find one. Since Rust builds are heavy and time-consuming, I wanted to cache as much as possible during the container build. Not only to speed up my pipeline, but also to reduce CI/CD costs at my current GitHub project.
# Install compilers for faster build
FROM rust:1.67.1 as chef
WORKDIR /app
RUN apt update && apt install lld clang -y
RUN cargo install cargo-chef --version 0.1.51
# Install cargo-chef and create recipe
FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
# Build dependencies for the project (not the app)
FROM chef AS cacher
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
# Copy caches and build the app
FROM chef AS builder
WORKDIR /app
COPY --from=cacher /app/target target
COPY --from=cacher /usr/local/cargo /usr/local/cargo
COPY . .
ENV SQLX_OFFLINE true
RUN cargo build --release --bin api-newsletter
# Production layer to run the app
FROM debian:buster-slim AS runtime
WORKDIR /app
RUN apt-get update -y \
&& apt-get install -y --no-install-recommends openssl \
&& apt-get autoremove -y && apt-get clean -y && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/api-newsletter api-newsletter
COPY configuration configuration
ENV APP_ENVIRONMENT production
ENTRYPOINT ["./api-newsletter"]
I hope you enjoy it as much as I do and it will save you a lot of time in the future. Let me know in the comments if you need help or have an idea on how to cache even more.
Member discussion