Sub topic 2
Measuring Image Size and Building Smaller Runtime Images
Assume you can read a Dockerfile, run docker build, and run a container. Image size includes the layers referenced by an image. A Dockerfile instruction usually creates a new layer, so copying unnecessary files or installing build tools can make the final image large.
Measure Before You Optimize
Build an image, then inspect it:
docker build -t myapp:small .
docker image ls myapp
docker history --no-trunc myapp:smalldocker image ls gives the image's overall size. docker history shows the layer sizes and the Dockerfile instruction that created each layer. Shared layers can be reused by several images, so the displayed image size is not always the exact additional disk space required.
| Command | Best use |
|---|---|
| `docker image ls` | Compare total image sizes |
| `docker history` | Find instructions that add large layers |
Choose a Base Image
The base image affects size, compatibility, and debugging:
- Full distributions are compatible and convenient, but large.
slimimages remove many tools while keeping common libraries.- Alpine is small, but its musl C library can expose compatibility problems.
- Distroless images contain runtime files without a shell or package manager.
scratchis empty. It works for self-contained static binaries only.
Choose the smallest base that supports the application, its libraries, certificates, and operational needs.
Build Only the Runtime
A multi-stage build uses separate FROM stages. The build stage contains compilers and dependencies. The final stage receives only the artifact needed at runtime.
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/app .
FROM scratch
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The final image does not contain the Go compiler or source code. COPY --from=build selects one file from the earlier stage.
Exercise
Which command helps identify the Dockerfile instruction responsible for a large layer?
Show answer
docker history --no-trunc IMAGE