FROM rust:slim-trixie
# lsof is used during the health check to see if the server is up
RUN apt-get update && apt-get install -y lsof
COPY ./Cargo.toml .
COPY ./Cargo.lock .
# We only want to cache dependencies from the Cargo.toml instead of copying and building the whole src,
# so we have to delete `[[bin]]`, `[[bench]]`, etc that points to a src file that won't exist.
RUN sed --in-place '/\[\[bin\]\]/,$d' ./Cargo.toml && cat ./Cargo.toml
# Cache crates in separate layer in case of build failures.
# Fetch crates before src/ COPY so crates aren't fetched every time src/ changes.
RUN mkdir ./src && \
# Create a fake source file so cargo won't error during build.
echo 'fn main() { println!("This is not the binary you are looking for!"); }' > ./src/main.rs && \
# Fetch and compile dependencies
cargo build --release && \
# Clean up the fake files
rm -Rvf ./src
# Copy the actual code and chown main.rs for the next step.
COPY --chown=1000 ./src ./src
# Invalidate rust cache and rebuild
RUN touch ./src/lib.rs && cargo build --release