Cloud and Container Basics
FROM alpine
COPY data.tar.gz /tmp/
RUN tar -xzf /tmp/data.tar.gz -C /opt && rm /tmp/data.tar.gzTo unpack a 500 MB archive, data.tar.gz, an image was built with the Dockerfile above. Although the archive was deleted in the same RUN after unpacking, the image remained larger by the size of the archive. Which of the following is the most appropriate pair of reason and remedy?
- AThe rm after && is not executed during the build. Write the rm as a separate RUN instruction
- BDeleted files remain in the image as build cache. Build again with --no-cache added to docker build
- CThe archive remains in the layer created by the COPY instruction. Use a multi-stage build and copy only the unpacked files into the final image
Show answer and explanation
Answer: C. The archive remains in the layer created by the COPY instruction. Use a multi-stage build and copy only the unpacked files into the final image
Each Dockerfile instruction that changes the file system (such as COPY or RUN) becomes one layer, and an image is these layers stacked together. Deleting a file in a later layer only records a deletion marker in the upper layer, so the 500 MB archive that went into the COPY layer remains in the image. With a multi-stage build that unpacks in another stage and brings only the unpacked files into the last stage with COPY --from, the archive is not included in the final image. Downloading, unpacking and deleting within one RUN is another approach, but it cannot be used for a file brought in with COPY.
- A. The rm after && also runs within the same RUN. Moving it to a separate RUN just adds a layer with the deletion marker and does not reduce the size.
- B. --no-cache only stops the results of earlier builds from being reused; the layer contents are the same, so the size does not change.
- C. Correct. The contents of a lower layer remain even after deletion, so keep the archive out of the final image.