Cloud and Container Basics
FROM golang AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app .
FROM scratch
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]scratch is an empty image that contains no files. Which of the following correctly describes what the final image built with the multi-stage Dockerfile above contains?
- AOnly the executable /app built in the build stage; the Go compiler and the source code are not included
- BThe layers of the build stage and the last stage are all stacked, so the Go compiler, the source code and /app are all included
- COnly the golang image of the first FROM and the source code; /app is built each time a container starts
Show answer and explanation
Answer: A. Only the executable /app built in the build stage; the Go compiler and the source code are not included
In a multi-stage build, each FROM starts a stage, and only the last stage becomes the final image. Earlier stages exist to produce artifacts with tools such as compilers, and only the files named in COPY --from are brought into the last stage. Here only /app is copied onto the empty scratch image, so the result is a small image without the Go compiler or the source code. Because scratch has no shared libraries either, CGO_ENABLED=0 is used to build an executable that does not depend on other libraries. Fewer contents mean faster pulls and fewer tools for attackers and fewer targets for vulnerabilities.
- A. Correct. Only the files brought into the last stage with COPY --from remain.
- B. The layers of earlier stages are not included in the final image. The final image is built from the last FROM.
- C. The final image is based on scratch in the last FROM, and go build runs only once, during the build.