2

I'm new to Docker, sorry if my question sounds dumb. below is a dockerfile from a textbook shows how multistage build works:

FROM diamol/base AS build-stage                  
RUN echo 'Building...' > /build.txt              

FROM diamol/base AS test-stage
COPY --from=build-stage /build.txt /build.txt
RUN echo 'Testing...' >> /build.txt             

FROM diamol/base
COPY --from=test-stage /build.txt /build.txt
CMD cat /build.txt

My questions is:

Why use multiple From instructions? why we don't do sth like:

FROM diamol/base AS build-stage                  
RUN echo 'Building...' > /build.txt              

COPY --from=build-stage /build.txt /build.txt
RUN echo 'Testing...' >> /build.txt             

COPY --from=test-stage /build.txt /build.txt
CMD cat /build.txt
2

First of all, you don't need the COPY instructions or multiple RUN instructions if you have only one stage:

FROM diamol/base AS build-stage
RUN echo 'Building...' > /build.txt && echo 'Testing...' >> /build.txt
CMD cat /build.txt

Of course, the textbook example is just that - an example to illustrate the concept.

In reality multistage builds are used to create smaller final images, while keeping the entire build process inside the container.

Generally speaking one may install all development and runtime dependencies in a build stage, then copy just the final distribution package to the final stage, where only runtime dependencies are installed to reduce the final image size.

For example:

FROM ubuntu:latest AS base
RUN apt -y install some-library

FROM base AS build
RUN apt -y install some-library-dev
COPY . /src
WORKDIR /src
RUN make && make install

FROM base
COPY --from=build /usr/bin/app /usr/bin/app
CMD /usr/bin/app

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.