Why is the rust docker image so huge

Viewed 776

I am packaging a rust app to a docker image to deploy to my server. I found the rust docker image size to be more than 1GB (larger than any other app using java and python). Why is the rust docker image so huge? I checked the layer and found the cargo build command takes more than 400MB.

FROM rust:1.54

LABEL maintainer="jiangtingqiang@gmail.com" 

ENV ROCKET_ADDRESS=0.0.0.0
ENV ROCKET_PORT=11014 

WORKDIR /app
COPY . .

RUN rustup default stable
RUN cargo build

CMD ["cargo", "run"]

Is it possible to make the rust docker image smaller?

1 Answers

The rust image is definitely not 1GB. From Dockerhub we can see that the images are far smaller. Your image is 1GB, because it contains all intermediate build artifacts which are not necessary for the functioning of the application - just check the size of the target folder on your PC

Rust image sizes:

+---------------+----------------+------------------+
|    Digest     |     OS/ARCH    |  Compressed Size |
+---------------+----------------+------------------+
| 99d3d924303a  | linux/386      | 265.43 MB        |
| 852ba83a6e49  | linux/amd64    | 196.74 MB        |
| 6eb0fe2709a2  | linux/arm/v7   | 256.59 MB        |
| 2a218d86ec85  | linux/arm64/v8 | 280.22 MB        |
+---------------+----------------+------------------+

The rust docker image contains the compiler, which you need to build your app, but you don;t have to package it with your final image. Nor you have to package all the temporary artifacts generated by the build process.

Solution

In order to reduce the final, production image, you have to use a multi-stage docker build:

  1. The first stage builds the image
  2. The second stage discards all irrelevant stuff and gets only the built application:
# Build stage
FROM rust:1.54 as builder
WORKDIR /app
ADD . /app
RUN cargo build --release

# Prod stage
FROM gcr.io/distroless/cc
COPY --from=builder /app/target/release/app-name /
CMD ["./app-name"]

Related