liveBook · Manning

Image optimization

As explained in Learn Docker in a Month of Lunches, Second Edition

Image optimization is the practice of reducing unnecessary content and construction overhead in container images.

Image optimization reduces unnecessary content and construction overhead in Docker images. Because each Dockerfile instruction creates a layer, deleting files later only hides them; the data still occupies image storage. Optimize every layer by copying only files the application needs and excluding irrelevant build-context content. section 17.1

Use this practical workflow:

  • Compare image sizes after building alternative Dockerfiles. section 17.1
  • Inspect docker history to reveal layers and their physical size, even when the merged filesystem hides deleted files. section 17.1
  • Make COPY instructions precise, then use .dockerignore to reduce build-context size and transfer time. 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 a Dockerfile that copies an entire directory and deletes documentation with the resulting layered image behavior. section 17.1

How Learn Docker in a Month of Lunches, Second Edition covers it

How deep it goes
Explains layered storage, demonstrates failed deletion cleanup, and stops short of broader image-hardening techniques.
Examples
Uses v1, v2, and v3 Dockerfiles, size comparisons, docker history, and a .dockerignore rebuild.
What you can do after
Apply it via Docker by inspecting layers and excluding files before they enter an image.
How it connects
Connects Dockerfiles with image layers, COPY instructions, build contexts, image history, and .dockerignore.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Docker in a Month of Lunches, Second Edition. The section links point to the parts of the book it draws on.