Difficulty: Intermediate
How do you see the layers of an image and the instructions that created them, and how would you use that to make an image smaller?
Run docker history <image>. It lists the image's layers from newest to oldest, showing for each one the instruction that created it (CREATED BY), when it was created and how much it added (SIZE). Add --no-trunc to see full commands. It is the quickest way to find which Dockerfile step makes an image big, and to see roughly how a third-party image was built.
CMD or ENTRYPOINT; the bottom rows are the base image.SIZE 0B rows come from metadata-only instructions (ENV, EXPOSE, CMD, LABEL, WORKDIR). Only RUN, COPY and ADD add content.IMAGE <missing> is normal. Layers pulled from a registry or built with BuildKit do not have intermediate image IDs on your machine; it does not mean anything is broken.COMMENT buildkit.dockerfile.v0 marks layers built by BuildKit.RUN npm install layer at 600 MB, or a COPY . . that is far larger than your source, points straight at the problem.RUN. A row that removes caches with 0B size means the files are still in the earlier layer; merge install and cleanup into one RUN.COPY . . usually means a missing .dockerignore (node_modules, .git or build output being copied).build-essential, dev dependencies) suggest moving to a multi-stage build that copies only the final artefact into a slim or distroless base.python:3.12 to python:3.12-slim often saves more than every other change combined.For deeper analysis, dive shows each layer's file tree and wasted space, and docker image inspect -f '{{json .RootFS.Layers}}' lists the layer digests.
COPY brought in.RUN commands and any secrets passed as ENV show up in --no-trunc output. Anyone who can pull the image can read them, which is why secrets belong in RUN --mount=type=secret, not in args or env.docker history.# Default view, newest layer first
docker history orders-api:2.3
# Full commands, human-readable sizes, custom columns
docker history --no-trunc --format 'table {{.Size}}\t{{.CreatedBy}}' orders-api:2.3
# Layer digests from the image config
docker image inspect -f '{{json .RootFS.Layers}}' orders-api:2.3
The SIZE column immediately shows that npm ci and COPY . . are the heavy layers worth optimising.
# Build stage: full toolchain and devDependencies
FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
# Runtime stage: only what production needs
FROM node:22-slim
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
CMD ["node", "dist/server.js"]
After this change, docker history of the final image shows only the slim base plus two small COPY layers.
docker history, Image layers, Layer size, Image optimisation, BuildKit