Sub topic 3
Which Dockerfile instructions create layers
This chapter assumes you can run docker build and docker run, read a simple Dockerfile, and know that an image is a stack of read-only layers. Here you learn which instructions add a filesystem layer and which only record metadata. That distinction explains image size, docker history output, and the build cache behavior covered in later chapters.
The rule: filesystem changes make layers
A layer stores a set of filesystem changes: files added, modified, or deleted. An instruction creates a layer only if it changes the filesystem. Instructions that only describe how to run the image write to the image configuration, which is a small JSON document.
In practice, three instructions produce filesystem layers:
RUNexecutes a command in a temporary container. Whatever the command changes on disk becomes the layer.COPYcopies files from the build context or from another stage into the image.ADDdoes whatCOPYdoes, plus it can fetch URLs and unpack local tar archives.
Everything else adds metadata only.
| Instruction | Layer type | What it records |
|---|---|---|
| `FROM` | Provides the base layers | The starting image |
| `RUN` | Filesystem layer | Files changed by the command |
| `COPY` | Filesystem layer | Files copied into the image |
| `ADD` | Filesystem layer | Files added or extracted |
| `WORKDIR` | Usually metadata, and a layer if it creates a missing directory | Working directory |
| `ENV` | Metadata | Environment variable |
| `ARG` | Metadata (build-time only) | Build argument |
| `LABEL` | Metadata | Key-value label |
| `EXPOSE` | Metadata | Documented port |
| `USER` | Metadata | Default user |
| `VOLUME` | Metadata | Declared mount point |
| `CMD` | Metadata | Default command |
| `ENTRYPOINT` | Metadata | Executable to run |
| `SHELL` | Metadata | Shell used by shell-form commands |
| `HEALTHCHECK` | Metadata | Health probe settings |
| `STOPSIGNAL` | Metadata | Signal sent on stop |
Seeing the difference in a build
Look at this Dockerfile. It has seven instructions after FROM, but only two of them add files.
FROM node:20-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]Here is how each step contributes:
FROMbrings in the layers ofnode:20-slim.WORKDIR /appcreates the directory if it does not exist. The directory is a filesystem change, so some builders store a small layer for it.ENVonly edits the image configuration.COPY package.json package-lock.json ./adds two files.RUN npm ciadds the contents ofnode_modules. This layer is often the largest.COPY . .adds the application source.RUN npm run buildadds the compiled output indist.CMDonly edits the configuration.
You can confirm this by building the image and listing its history, which the following chapters cover in detail.
docker build -t myapp:dev .
docker history myapp:devSteps that only change metadata show 0B in the SIZE column. Steps that write files show a size greater than zero.
RUN: the layer is the diff, not the command
A RUN layer contains the difference between the filesystem before and after the command. The layer does not store the command's output text or the command itself. The command text appears only in the image history.
This has three consequences.
- A command that changes nothing on disk produces an empty layer, or no layer at all, depending on the builder.
- A command that touches many files can produce a large layer even if the command is short. Running
chown -Ron a large directory, for example, copies every file into the new layer, because changing ownership modifies each file. - Temporary files that remain at the end of the step are stored in the layer.
Because the layer is a diff, cleanup only works when it happens in the same RUN step that created the files. The following example does it correctly: the package index is downloaded, used, and removed within one step, so it never reaches a stored layer.
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*A later chapter explains why deleting files in a later RUN cannot reclaim the space.
COPY and ADD: the layer is the files
A COPY layer contains the copied files with their paths, permissions, and ownership. Three details matter.
- By default, copied files are owned by root. Use
COPY --chown=user:groupto set ownership during the copy. RunningRUN chown -Rafter a plainCOPYduplicates the files in a second layer. - Docker decides whether the step can be reused by checking the content of the files being copied. File modification times are not part of that check.
COPY --from=<stage>copies files out of an earlier build stage or another image. Only those files enter the new layer.
ADD has extra behavior, and that is the reason to prefer COPY in most cases. ADD extracts local tar archives automatically, and it can download from a URL. A downloaded file is stored in the layer as is, so you cannot unpack and remove it within the same step. For remote files, a RUN curl ... | tar -x step in a single command is often smaller.
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSL https://example.com/tool.tar.gz | tar -xz -C /optThis pipeline never writes the archive to disk, so no archive exists to remove later.
The edge cases
FROM and the base layers
FROM does not create a new layer. It sets the starting point, and the layers of the base image become the lowest layers of your image. In a multi-stage build, each FROM begins a new stage with its own layers. Only the layers of the final stage end up in the image you ship, unless you target another stage.
WORKDIR
WORKDIR sets the directory for later instructions. If the directory is missing, the builder creates it, which is a filesystem change. Whether you see a layer for this depends on the builder version, so treat WORKDIR as "a possible tiny layer" and never rely on either outcome.
VOLUME
VOLUME records a mount point in the configuration. It adds no layer. It has a side effect that surprises people: changes made to that path by later RUN steps are discarded in the build, because the path is treated as a volume. Place VOLUME after any step that writes to that directory.
USER, ENV, and ARG
None of these writes files, so none adds a layer. They still affect later steps. A RUN after USER app runs as that user, and a changed ENV value changes the cache key of every later step. ARG values are visible in docker history, so do not pass secrets through them.
Empty and no-op steps
Some steps do nothing visible, such as RUN true. Treat them as waste: they still occupy a history entry and a cache entry.
Counting layers: a short experiment
You can check which steps changed the filesystem by listing the layer digests next to the history.
docker image inspect --format '{{len .RootFS.Layers}}' myapp:dev
docker history --format '{{.Size}}\t{{.CreatedBy}}' myapp:devThe first command prints the number of filesystem layers in the image. The second prints one line per history entry. The two numbers differ because metadata-only steps appear in the history but not in the layer list. This gap is the clearest way to see the rule from this chapter.
Common mistakes
- Treating every instruction as a layer. Counting
ENVandCMDas layers leads to wrong advice, such as merging them to "save layers". Merging metadata instructions saves nothing. - Merging everything into one RUN. Combining unrelated commands removes useful cache boundaries. Merge only the steps that must share cleanup, such as
update,install, and removing the lists. - Using
chown -Rafter COPY. UseCOPY --chowninstead. - Using ADD for plain copies. Its extra behavior can surprise you. Use
COPYunless you need extraction or a URL. - Writing under a declared VOLUME. Changes after the
VOLUMEline are lost.
Summary
Only steps that change files store a layer, mainly RUN, COPY, and ADD. Metadata instructions change the configuration. Each RUN layer is a diff, so cleanup must happen in the same step. The next chapter uses this rule to explain when the build cache reuses a step.
Exercise
A Dockerfile has FROM debian:bookworm-slim, ENV MODE=prod, RUN apt-get update && apt-get install -y curl, COPY app.sh /app.sh, EXPOSE 8080, and CMD ["/app.sh"]. How many layers does your build add on top of the base image, and why?
Show answer
Two. The RUN step writes installed files and package lists, and the COPY step adds app.sh. ENV, EXPOSE, and CMD only change the image configuration, and FROM supplies the base layers instead of adding one.
Exercise
You copy data.tar.gz into an image with COPY, extract it in a second RUN, and then delete the archive in a third RUN. The image is still large. What change would keep the archive out of the image?
Show answer
Download or stream the archive and extract it within a single RUN, for example curl -fsSL URL | tar -xz -C /opt, so the archive is never written to a layer. Alternatively, use a multi-stage build and copy only the extracted files into the final stage. Deleting the archive in a later step only hides it, because the earlier layer still stores it.