Make Cargo Usable in Docker ๐Ÿ“ฆ

10x your workflow with containerised Rust builds

I've tried it all: specifying cache layers, cargo-chef, cargo vendor , and workarounds from across the internet, but cargo inside a Docker container is still excruciatingly slow.

I'm talking over ten fekin minutes on first build.

Cargo isn't optimised to take advantage of Docker's layer caching, typically rebuilding more than necessary each run.

FROM rust:1.67

WORKDIR /usr/src/myapp
COPY . .

RUN cargo install --path .

CMD ["myapp"]
rust's official Dockerfile

Issue

  • Microservices must be containerised eventually, and docker-compose is orchestration little-league.
  • The cargo-watch crate makes for much shorter iteration cycles, enabling hot reload on source changes akin to nodemon for NodeJS.

Previously, you had to install cargo-watch and dependencies, as shown below.

FROM rust:1.67

EXPOSE 6767
WORKDIR /app

COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN cargo install --path .

COPY . .

RUN cargo install cargo-watch
CMD ["cargo", "watch", "-q", "-w", "src", "-x", "run" ]

Fix

I've prebaked these requirements into a base container called cargo-base. Now, not only is cargo-watch built-in, but so is the cargo cache - making installing crates much faster.

You can use the base image below for development. Change CMD or revert to the standard rust image when ready for production. Enjoy_

FROM yohanderose/cargo-base:1.67

EXPOSE 6767
WORKDIR /app

COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN cargo install --path .

COPY . .

CMD ["cargo", "watch", "-q", "-w", "src", "-x", "run" ]