Skip to content

Instantly share code, notes, and snippets.

@skyscribe
Last active March 16, 2023 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skyscribe/c929da9dda933e84caab97ae11724a4e to your computer and use it in GitHub Desktop.
Save skyscribe/c929da9dda933e84caab97ae11724a4e to your computer and use it in GitHub Desktop.
Build slim rust with alpine and cargo chef

To create a slim rust docker image, one needs to do the following with below assumptions

  • The project would generate a binary tool called ims2_tool
  • Its version is annotated in clap derive API, so the script could fetch the version directly from source code.
  1. Create a multi-stage docker file, see Dockerfile
  2. Modify your project's Cargo.toml file so desired [[bin]] section must exist, otherwise docker build would fail during cargo prepare phase.
[[bin]]
name="<executable name>"
bench=false
test=false
  1. Create a build_docker.sh to update your image easily.
#!/usr/bin/env bash
cargo clean
version=$(cat src/cli/app.rs | sed -n "s/.*version\s*=[^vV]*\([0-9vV.]\+\).*/\1/gp")
echo "Will build for ${version}..."
sudo docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy -t nsbboamfh/ims2parser:$version .
[ $? -eq 0 ] && sudo docker push nsbboamfh/ims2parser:$version
FROM docker-registry-remote.artifactory-espoo1.int.net.nokia.com/rust:1.66-alpine as chef
RUN apk add --no-cache musl-dev
RUN cargo --version
RUN cargo install cargo-chef
WORKDIR /app
FROM chef as planner
COPY Cargo.toml Cargo.lock ./
RUN cargo chef prepare --recipe-path recipe.json
FROM chef as builder
COPY --from=planner /app/recipe.json recipe.json
COPY --from=planner /app/Cargo.toml /app/Cargo.lock ./
# Build dependencies
RUN cargo chef cook --release --recipe-path recipe.json
# Build applications
COPY src src/
RUN cargo build --release
# Deploy image
FROM docker-registry-remote.artifactory-espoo1.int.net.nokia.com/alpine:3.17
RUN cp --from=builder /app/target/release/ims2_tool /usr/bin/
ENTRYPOINT [ "/usr/bin/ims2_tool" ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment