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
