Sub topic 5
Why images get large
This chapter covers where the bytes in a container image come from. You need to know that before you can cut them. It assumes you can build and run an image with docker build and docker run, and that you have read a simple Dockerfile. The chapter on layers explains the layer mechanics in more detail. Here we use only the one fact we need: an image is the sum of its layers, and a layer never gets smaller once it exists.
The working model: size is additive
Each filesystem-changing instruction (RUN, COPY, ADD) produces a layer that stores the files it added, changed or marked as deleted. The final image size is roughly the sum of all layer sizes. Deleting a file in a later layer hides it from the running container, but the layer that first added it still ships with the image.
Most oversized images come from five sources:
- The base image.
- Build tools left in the final image.
- Package manager caches and metadata.
- Dependencies the app does not use at runtime.
- Files copied in that should not be there.
Source 1: the base image
The FROM line sets the floor. Every byte of the base image is in your image, whether or not your app uses it. A full distribution image includes a shell, a package manager, many shared libraries and utilities. A language image such as golang or node adds the compiler, interpreter and often a C toolchain on top.
| Base image | Approximate size | What you get |
|---|---|---|
| `golang:1.22` | several hundred MB | Go toolchain, git, gcc and other build tools |
| `node:20` | about 1 GB | Node, npm, Python and a C toolchain |
| `node:20-slim` | about 200 MB | Node and npm, few extra packages |
| `scratch` | 0 bytes | Nothing |
Sizes change from release to release, so treat the numbers as orders of magnitude and measure your own. The chapter on choosing a base image compares the options in detail. The point here is that picking the base image is the first size decision you make, and it is often the biggest.
Source 2: build tools left behind
Compilers, header files, and tools like git and make are needed to build the app but not to run it. If you build in the same stage you ship, all of them stay in the final image. They also enlarge the attack surface: a compiler in a production container is a tool an attacker can use.
A single-stage Go image shows the cost. The compiled binary may be 10 MB, but the image also contains the whole Go toolchain, the module cache and the source tree. This is the main problem that multi-stage builds solve, and the following chapters cover it.
Source 3: package manager caches and metadata
Package managers keep data you do not need after installation:
apt-get updatedownloads package lists into/var/lib/apt/lists/.apt-get installalso installs "recommended" packages unless you say otherwise.pipstores downloaded wheels in a cache directory.npmkeeps a cache in the home directory.
These files are small per package but add up across a build. The usual fix is to clean up in the same RUN instruction that created them.
Why cleanup must happen in the same layer
This is the most common error in size-conscious Dockerfiles. Compare these two versions:
FROM debian:bookworm-slim
# Bad: the package lists are written in one layer and deleted in another
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*FROM debian:bookworm-slim
# Better: download, install and clean up in a single layer
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*In the first version, the rm creates a layer that marks the files as deleted, but the apt-get update layer still holds the full package lists. The image is exactly as large as if the rm line were missing. In the second version, the lists are removed before the layer is committed, so they never become part of it. The same holds for any temporary file: a downloaded archive, a source tarball, a build directory. If you create it and delete it in separate instructions, you ship it.
The second version also adds --no-install-recommends, which skips optional packages and often saves tens of megabytes on its own.
Source 4: dependencies you do not need at runtime
Installing dependencies naively pulls in everything the project declares. In Node.js, npm ci installs devDependencies such as test runners, linters and bundlers. In Python, a single requirements.txt may include test and documentation packages. A project with a large node_modules directory can easily have hundreds of megabytes of packages that never run in production.
There are two ways to avoid shipping them:
- Install only production dependencies in the final image (for example
npm ci --omit=dev). - Build in one stage, then copy only the built output into a clean final stage.
The Node.js and Python examples later in this tutorial use both.
Source 5: files you copy in by accident
COPY . . copies the whole build context into the image. The build context is the directory you pass to docker build, and everything in it is sent to the builder. If that directory contains a .git folder, a local node_modules, logs, test data or .env files, they all go into the image.
This has three costs:
- Size: a repository's
.gitdirectory can be larger than the source code. - Cache misses: any change to an irrelevant file, such as a log file, changes the layer that copied it and invalidates the cache for every later step.
- Leaks: a copied
.envfile puts credentials into a layer that anyone who can pull the image can read.
A .dockerignore file excludes paths from the context. The next chapters cover it in more detail.
A related trap: changing ownership after copying
Files copied in as root often need to belong to another user. This tempting version doubles their size:
FROM node:20-slim
WORKDIR /app
COPY . .
RUN chown -R node:node /appThe chown rewrites the metadata of every file, so each file is stored again in the new layer. Set ownership while copying instead:
FROM node:20-slim
WORKDIR /app
COPY --chown=node:node . .The same applies to chmod -R. Running either one over a large directory in its own RUN instruction creates a second copy of that directory in the image.
Smaller causes worth knowing
- Debug symbols: compiled binaries include symbol tables by default. Go's
-ldflags="-s -w"strips them and often cuts the binary by a quarter or more. - Multiple copies of the same data: downloading an archive with
ADDorRUN curl, extracting it and leaving the archive in place stores the data twice. - Large files in the repository: datasets, model weights and media files copied into the image. If the app can fetch these at startup or read them from a volume, keep them out.
- Language-level bloat: Python's
__pycache__directories and test folders inside installed packages are small but common.
Diagnosing a large image
When an image is larger than you expect, work through the sources in order:
- Check the base image. Is a slimmer variant available?
- Look for build tools in the final image: compilers,
git,make. - Look for
RUNinstructions that delete files created in an earlier instruction. - Check whether dev dependencies are installed.
- Check what
COPY . .brings in, and whether a.dockerignorefile exists.
You can find the heavy layers with docker history, which a later chapter covers.
Exercise
A Dockerfile has three lines: RUN curl -o /tmp/data.tar.gz https://example.com/data.tar.gz, then RUN tar -xzf /tmp/data.tar.gz -C /opt, then RUN rm /tmp/data.tar.gz. The author expected the rm to shrink the image, but the image size did not change. Why, and how would you fix it?
Show answer
Each RUN creates its own layer. The first layer stores the downloaded archive, and the rm in the third layer only marks the file as deleted in that later layer, so the archive still ships in the first layer. Combine the steps into one instruction, such as RUN curl -o /tmp/data.tar.gz https://example.com/data.tar.gz && tar -xzf /tmp/data.tar.gz -C /opt && rm /tmp/data.tar.gz. The archive is then removed before the layer is committed. Alternatively, pipe curl directly into tar -xz so the archive is never written to disk.
Exercise
A team uses COPY . . followed by RUN chown -R app:app /app. Name two ways this makes the image larger or the build slower, and give a fix for each.
Show answer
First, the chown -R rewrites ownership metadata for every file, so the files are stored a second time in a new layer and the image grows. Use COPY --chown=app:app . . to set ownership in the copying layer. Second, COPY . . copies everything in the build context, including .git, local dependencies and logs, which adds size and invalidates the cache whenever those files change. Add a .dockerignore file that excludes them.