Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dockerfile build remove source code from final image

I am new to Docker. I want to build a docker image by building a c++ library using make command. The way I am doing it in Dockerfile is that

  • copy the source code from host
  • install required packages
  • run make
  • copy the libraries (.so) into different folder inside the image
  • delete the source code

The Dockerfile code is written below.

The problem I am facing is that even after deleting the source code the final image size is big.

Since each line of Dockerfile creates a different layer, there is a way to download the source code using curl or wget and later delete the source code in the same layer. But I don't like the solution.

FROM alpine

RUN apk update && apk add <required_packages>

COPY source_code /tmp/source_code

RUN make -C /tmp/source_code && \
        mkdir /libraries/
        cp /tmp/lib/* /libraries/
        rm -rf /tmp/*

I just want to minimize the final image size. Is it the right way I am doing this or is there any better way? Please help.

like image 623
shubham pagui Avatar asked Apr 16 '26 06:04

shubham pagui


1 Answers

You can do a multi-stage build and copy the artifacts on a new image from the previous one. Also install any required runtime dependencies (if any).

FROM alpine AS builder

RUN apk add --no-cache <build_dependencies>

COPY source_code /tmp/source_code

RUN make -C /tmp/source_code && \
        mkdir /libraries/
        cp /tmp/lib/* /libraries/
        rm -rf /tmp/*

FROM alpine

RUN apk add --no-cache <runtime_dependencies>

COPY --from=builder /libraries/ /libraries/
like image 146
codestation Avatar answered Apr 19 '26 07:04

codestation



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!