HiveBrain v1.2.0
Get Started
← Back to all entries
patterndockerMinor

why use multiple From instructions in multistage build?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
whyinstructionsmultiplemultistagefrombuilduse

Problem

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

Solution

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

Code Snippets

FROM diamol/base AS build-stage
RUN echo 'Building...' > /build.txt && echo 'Testing...' >> /build.txt
CMD cat /build.txt
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

Context

StackExchange DevOps Q#12267, answer score: 2

Revisions (0)

No revisions yet.