Skip to content

Instantly share code, notes, and snippets.

@tdelmas
Created June 25, 2025 18:25
Show Gist options
  • Select an option

  • Save tdelmas/d1aff66ff49d4693d4e4153ac7489112 to your computer and use it in GitHub Desktop.

Select an option

Save tdelmas/d1aff66ff49d4693d4e4153ac7489112 to your computer and use it in GitHub Desktop.
Rust distroless dockerfile for multi stage build with shared libraries
# ------------------------------------------------------------------------------
# Cargo Build Stage
# ------------------------------------------------------------------------------
# Same base as distroless/base-debian12
FROM rust:1.87-bookworm AS cargo-build
RUN apt-get update
RUN apt-get install --only-upgrade -y ca-certificates
WORKDIR /usr/src/
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch --locked
RUN mkdir src/
# Create a dummy main.rs file to pre-build the dependencies
RUN echo "fn main() { panic!(\"Compilation failed\"); }" > src/main.rs
# Pre-build the dependencies
RUN cargo build --release --offline --locked
COPY ./src ./src
# Invalidate cargo cache (original main.rs is older than the dummy one)
RUN touch -a -m ./src/main.rs
RUN cargo build --release --offline --locked
RUN cargo install --path . --root . --offline --locked
RUN ls ./bin && ls ./bin/app
RUN mkdir ./bin/x86_64-linux-gnu
RUN ldd ./bin/server \
| sed -e 's/.*=>//' | sed -e 's/(.*//' | sed 's/[[:space:]]//g' \
| grep '^/lib/x86_64-linux-gnu/' \
| sort | uniq \
| xargs -I {} cp -v {} ./bin/x86_64-linux-gnu/
# ------------------------------------------------------------------------------
# Final Stage
# ------------------------------------------------------------------------------
FROM gcr.io/distroless/base-debian12:nonroot
ENV PORT=8080
# Copy the required shared libraries
COPY --from=cargo-build --chown=0:0 --chmod=444 /usr/src/app/bin/x86_64-linux-gnu/* /lib/x86_64-linux-gnu/
# Updated certificates files
COPY --from=cargo-build --chown=0:0 --chmod=444 /etc/ca-certificates.conf /etc/ca-certificates.conf
COPY --from=cargo-build --chown=0:0 --chmod=444 /etc/ssl/certs /etc/ssl/certs
# Copy the server binary. Execute only.
COPY --from=cargo-build --chown=0:0 --chmod=111 /usr/src/server/bin/server /usr/local/bin/
EXPOSE $PORT/tcp
CMD ["/usr/local/bin/app"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment