Make rust compilation faster in Docker.
Closed this issue · 1 comments
DilecPadovani commented
Currently the dockerfile
to build the API itself is :
FROM rustlang/rust:nightly
RUN apt install -y libpq-dev git
WORKDIR /~
COPY Rocket.toml .
COPY Cargo.toml .
COPY diesel.toml .
COPY src src
COPY migrations migrations
RUN cargo build --release
ENTRYPOINT ["target/release/rocket_diesel_demo"]
What is to be achieved?
- Reduce build time, maybe using
cargo vendor
- Remove src files, by doing something like this:
FROM rust:1.61.0 as builder
WORKDIR /usr/src/myapp
COPY . .
RUN cargo install --path .
FROM debian:buster-slim as runner
RUN apt-get update && apt-get install -y extra-runtime-dependencies && rm -rf /var/lib/apt/lists/*
COPY --from=builder /usr/local/cargo/bin/myapp /usr/local/bin/myapp
CMD ["myapp"]
DilecPadovani commented
The solution i came up with involves cargo chef
, a crate created to solve the issue of downloading and building dependencies every time docker-compose up --build
is invoked.
# Stage1 : fetch needed dependecies
FROM rust:latest as dep-fetcher
WORKDIR /app
RUN cargo install cargo-chef
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
# Stage2: build needed dependecies
FROM rust:latest as dep-builder
WORKDIR /app
# RUN cargo install cargo-chef
COPY --from=dep-fetcher /usr/local/cargo /usr/local/cargo
COPY --from=dep-fetcher app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
# Stage3: compile the app
FROM rust:latest as builder
COPY . /app
WORKDIR /app
COPY --from=dep-builder app/target target
COPY --from=dep-builder /usr/local/cargo /usr/local/cargo
RUN cargo build --release
# Stage4: run the app
FROM debian:stable-slim as runtime
RUN apt-get update -y
RUN apt-get install libpq-dev -y
COPY Rocket.toml Rocket.toml
COPY --from=builder /app/target/release/rocket_diesel_demo /app/rocket_diesel_demo
WORKDIR /app
CMD ["./rocket_diesel_demo"]