An image can consume space even when its container cannot see every file it contains. Image size reflects the image’s layers, not just the files visible in the merged container filesystem. Check sizes when builds fill a machine’s disk, take longer to transfer, or include software the application does not need. section 17.1 section 17.2
Each Dockerfile instruction creates a layer. If `COPY . .` adds an unused `docs` directory, a later `RUN rm -rf docs` hides it from containers but does not remove it from the earlier layer. To reduce image size, avoid copying the directory in the first place—for example, use `COPY ./app ./app`. A `.dockerignore` file can also reduce the build context and the time spent sending it; that is a separate benefit from reducing the resulting image. section 17.1
Listing 17.1 Trying to optimize a Dockerfile by removing files
# Dockerfile v1 – copies in the whole directory structure: FROM diamol/base:2e CMD echo app- && ls app && echo docs- && ls docs COPY . . # Dockerfile v2 – adds a new step to delete unused files FROM diamol/base:2e CMD echo app- && ls app && echo docs- && ls docs COPY . . RUN rm -rf docs
Compare the two Dockerfiles: the second deletes files only after the first layer has already added them. section 17.1
Measure what a deletion changes
From `ch17/exercises/build-context`, build the default Dockerfile with `docker image build -t diamol/ch17-build-context:2e-v1 .`, then build the second with `docker image build -t diamol/ch17-build-context:2e-v2 -f ./Dockerfile.v2 .`. Run `docker image ls "diamol/ch17-build-context*"` to compare sizes: they are the same. Run `docker history diamol/ch17-build-context:2e-v2` to inspect the layer sizes. The deleted directory is hidden when you run the second image, but its earlier layer remains. section 17.1
Base-image choice matters too. Test a smaller runtime image instead of shipping development tools the running application does not need. Java 22 image variants differ substantially in size; Alpine or Debian Slim on Linux and Nano Server on Windows are options to test, but not every application works with them. Smaller images can also leave fewer tools available to someone who compromises a container. section 17.2
Table 17.1 Size differences between compatible Java 22 images on Docker Hub
|
eclipse-temurin
|
:22-jdk
|
:22-jre
|
:22-jre-alpine
|
:22-jre-nanoserver
|
|---|---|---|---|---|
|
440 MB
|
281 MB
|
189 MB
|
||
|
3.78 GB
|
3.45 GB
|
444 MB
|
Use the Java 22 variant sizes to compare development and runtime bases before testing a smaller choice with your application. section 17.2
A multi-stage Go build gives another comparison: the image containing Go tools is about 230 MB on Linux, while the application image is about 35 MB. Those are virtual image sizes, so shared layers affect actual disk savings. The clear gain is that the final image does not contain the Go tools. section 4.4

