Template Dockerfile for Rust programming languages.
A common version that you usually see:
FROM rust:1.70.0-slim-bullseye # View app name in Cargo.toml
ARG APP_NAME=devopsvn WORKDIR /app COPY . .
RUN cargo build --locked --release
RUN cp ./target/release/$APP_NAME /bin/server ENV ROCKET_ADDRESS=0.0.0.0
CMD ["/bin/server"]
But it doesn't reuse cache layer and optimizes. Reuse cache layer for build faster:
FROM rust:1.70.0-slim-bullseye # View app name in Cargo.toml
ARG APP_NAME=devopsvn WORKDIR /app COPY Cargo.lock Cargo.toml ./
RUN mkdir src \ && echo "// dummy file" > src/lib.rs \ && cargo build --release COPY src src
RUN cargo build --locked --release
RUN cp ./target/release/$APP_NAME /bin/server ENV ROCKET_ADDRESS=0.0.0.0
CMD ["/bin/server"]
Optimize Image size with multi-stage:
FROM rust:1.70.0-slim-bullseye AS build # View app name in Cargo.toml
ARG APP_NAME=devopsvn WORKDIR /build COPY Cargo.lock Cargo.toml ./
RUN mkdir src \ && echo "// dummy file" > src/lib.rs \ && cargo build --release COPY src src
RUN cargo build --locked --release
RUN cp ./target/release/$APP_NAME /bin/server FROM debian:bullseye-slim AS final
COPY --from=build /bin/server /bin/
ENV ROCKET_ADDRESS=0.0.0.0
CMD ["/bin/server"]
With non-privileged users:
FROM rust:1.70.0-slim-bullseye AS build # View app name in Cargo.toml
ARG APP_NAME=devopsvn WORKDIR /build COPY Cargo.lock Cargo.toml ./
RUN mkdir src \ && echo "// dummy file" > src/lib.rs \ && cargo build --release COPY src src
RUN cargo build --locked --release
RUN cp ./target/release/$APP_NAME /bin/server FROM debian:bullseye-slim AS final RUN adduser \ --disabled-password \ --gecos "" \ --home "/nonexistent" \ --shell "/sbin/nologin" \ --no-create-home \ --uid "10001" \ appuser
USER appuser COPY --from=build /bin/server /bin/
ENV ROCKET_ADDRESS=0.0.0.0
CMD ["/bin/server"]
For other programming language, check here: Dockerfile for many programming languages.