title: Rust docker image with small binary
body: <p>I am trying to dockerise a simple server written in Rust using Rocket.
  I managed to get a simple image working but found the image size to be massive. When trying to shrink it I have tried two different things, both seems to result in the same issue. <code>docker exec &lt;name&gt; exited with code 126</code>
  It seems like the arbdata.exe file is not being copied across properly.</p>
  <p>working Dockerfile (big image)</p>
  <pre><code>FROM rust
  
  COPY . /app
  
  WORKDIR /app
  
  RUN cargo build --release
  
  CMD [&quot;./target/release/arb_data&quot;]
  </code></pre>
  <p>first attempt at smaller image</p>
  <pre><code>FROM rust as builder
  WORKDIR /app
  COPY ./ /app
  RUN cargo build --release
  # gcr.io/distroless/cc-debian11
  # rust:slim-buster
  # FROM gcr.io/distroless/cc
  FROM gcr.io/distroless/cc
  COPY --from=builder /app/target/release/arb_data .
  CMD [&quot;./arb_data&quot;]
  </code></pre>
  <p>second attempt at a smaller image</p>
  <pre><code>ARG BINARY_NAME_DEFAULT=arbdata
  
  FROM clux/muslrust:stable as builder
  RUN groupadd -g 10001 -r dockergrp &amp;&amp; useradd -r -g dockergrp -u 10001 dockeruser
  ARG BINARY_NAME_DEFAULT
  ENV BINARY_NAME=$BINARY_NAME_DEFAULT
  
  # Build the project with target x86_64-unknown-linux-musl
  
  # Build dummy main with the project's Cargo lock and toml
  # This is a docker trick in order to avoid downloading and building 
  # dependencies when lock and toml not is modified.
  COPY Cargo.lock .
  COPY Cargo.toml .
  RUN mkdir src \
      &amp;&amp; echo &quot;fn main() {print!(\&quot;Dummy main\&quot;);} // dummy file&quot; &gt; src/main.rs
  RUN set -x &amp;&amp; cargo build --target x86_64-unknown-linux-musl --release
  RUN [&quot;/bin/bash&quot;, &quot;-c&quot;, &quot;set -x &amp;&amp; rm target/x86_64-unknown-linux-musl/release/deps/${BINARY_NAME//-/_}*&quot;]
  
  # Now add the rest of the project and build the real main
  COPY src ./src
  RUN set -x &amp;&amp; cargo build --target x86_64-unknown-linux-musl --release
  RUN mkdir -p /build-out
  RUN set -x &amp;&amp; cp target/x86_64-unknown-linux-musl/release/$BINARY_NAME /build-out/
  
  # Create a minimal docker image 
  FROM scratch
  
  COPY --from=0 /etc/passwd /etc/passwd
  USER dockeruser
  
  ARG BINARY_NAME_DEFAULT
  ENV BINARY_NAME=$BINARY_NAME_DEFAULT
  
  ENV RUST_LOG=&quot;error,$BINARY_NAME=info&quot;
  COPY --from=builder /build-out/$BINARY_NAME /
  
  # Start with an execution list (there is no sh in a scratch image)
  # No shell =&gt; no variable expansion, |, &lt;, &gt;, etc 
  # Hard coded start command
  CMD [&quot;/arbdata&quot;]
  </code></pre>
  <p>here is a link to the <a href="https://github.com/putintin420/arb_data" rel="nofollow noreferrer">github repo</a> with the working api.</p>