Sub topic 2
Anatomy of a Dockerfile
This chapter covers how a Dockerfile is parsed and what its instructions look like. It assumes you can use a terminal, have Docker installed, and know that a container is an isolated process started from an image. Later chapters cover each instruction in depth. Here you learn the structure they all share, so you can read any Dockerfile and predict what Docker will do with it.
A Dockerfile is a list of instructions
A Dockerfile is a plain text file, usually named Dockerfile with no extension, that describes how to build an image. Docker reads it from top to bottom and runs each instruction in order. Most instructions that change the filesystem produce a new layer, which is a stored set of file changes. Other instructions only record metadata, such as the default command or an environment variable.
Here is the Node.js Dockerfile you will use throughout this tutorial:
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]Every line has the same shape: an instruction name, then its arguments.
INSTRUCTION argumentsInstruction names are not case-sensitive, but the convention is uppercase. It makes instructions easy to tell apart from the commands and paths in their arguments.
How Docker reads the file
Docker's parser follows a few simple rules. Knowing them prevents most syntax errors.
- One instruction per line. The first word on a line is the instruction. Everything after it is the argument.
- Comments start with
#. A comment must be on its own line. A#after an instruction is passed to the instruction as part of its arguments. - Blank lines are ignored.
- A backslash at the end of a line continues the instruction on the next line. This keeps long
RUNcommands readable. - The first real instruction must be
FROM. OnlyARGand comments may come before it, becauseFROMselects the base the rest of the file builds on.
The comment rule catches people out. This line does not do what it appears to do:
RUN echo "building" # print a messageThe shell receives echo "building" # print a message. It treats # as a shell comment, so the result is harmless here. In other instructions, the trailing text becomes part of the value. Put comments on their own lines.
Line continuation
Long commands are easier to review when each part is on its own line:
FROM debian:bookworm-slim
# Install tools in one step so the package index is never stale
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*Docker joins the three lines into one instruction before running it. Because the update, install, and cleanup all happen in a single RUN, they end up in one layer. Cleanup in a later RUN would not shrink the image, because the earlier layer would still contain the deleted files.
Instruction categories
Instructions fall into three groups, which matters when you reason about layers and caching.
| Group | Instructions | Effect |
|---|---|---|
| Build the filesystem | `FROM`, `COPY`, `ADD`, `RUN` | Start from a base image, or add files to the image. These add layers that contain files. |
| Set defaults for the container | `ENV`, `WORKDIR`, `USER`, `CMD`, `ENTRYPOINT`, `EXPOSE`, `HEALTHCHECK`, `LABEL` | Record metadata stored in the image configuration. They affect how a container starts, not what files it contains. `WORKDIR` also creates the directory if it is missing. |
| Build-time only | `ARG` | Defines a variable that exists while building. It is not stored as a runtime environment variable. |
Metadata instructions still appear in the image's history, and they still take part in the build cache. They add no file content, so they cost almost nothing in size.
Reading the example line by line
Walking through the Node.js file shows how the groups fit together.
FROM node:20-slimselects the starting filesystem. Everything below builds on top of it.WORKDIR /appsets the working directory for the instructions that follow and for the running container. Docker creates/appif it does not exist.COPY package*.json ./copies the dependency manifests from the build context into/app. The destination is relative toWORKDIR.RUN npm ci --omit=devruns a command inside a temporary container and saves the resulting filesystem changes as a layer.COPY . .copies the rest of the source into/app.ENV NODE_ENV=productionsets an environment variable that persists in the image and is visible to the running app.EXPOSE 3000documents the port the app listens on. It does not publish the port.USER nodemakes later instructions and the final container run as the unprivilegednodeuser.CMD ["node", "server.js"]sets the default command for a container.
The order is deliberate. The dependency manifests are copied before the source so that the install layer is reused when only source files change. Chapter 9 covers this in detail. For now, notice that the file reads as a recipe: base, location, files, install, more files, settings, command.
Two forms for arguments
Several instructions accept their arguments in two forms. The difference affects how the command is run, so it is worth learning early.
- Shell form is plain text:
RUN npm ci --omit=dev. Docker runs it through a shell,/bin/sh -con Linux. Shell features such as&&, pipes, and variable expansion work. - Exec form is a JSON array:
CMD ["node", "server.js"]. Docker runs the program directly with no shell. There is no variable expansion or chaining.
Exec form must be valid JSON. Use double quotes, not single quotes. A single-quoted array is not valid JSON, so Docker falls back to treating the whole line as shell form, which produces confusing behavior rather than a clear error.
# Valid exec form
CMD ["node", "server.js"]
# Not valid JSON: treated as shell form, and the command will fail
CMD ['node', 'server.js']The two forms matter most for CMD and ENTRYPOINT, where exec form lets your app receive signals such as SIGTERM directly. Chapter 7 covers that.
Variables inside a Dockerfile
Some instructions expand variables written as $NAME or ${NAME}. This works for ENV and ARG values in instructions such as WORKDIR, COPY, ADD, USER, and ENV itself.
FROM node:20-slim
ENV APP_HOME=/app
WORKDIR $APP_HOME
COPY . $APP_HOMEDo not confuse this with shell expansion. In shell form, the shell expands variables when the command runs. In exec form, no shell is involved, so CMD ["echo", "$APP_HOME"] prints the literal text $APP_HOME. Chapter 6 covers ENV and ARG in full.
Parser directives
A parser directive is a special comment at the very top of the file that changes how Docker parses it. The most common one selects the Dockerfile syntax version used by BuildKit, the modern build engine:
# syntax=docker/dockerfile:1
FROM alpine:3.20
RUN echo "hello"Directives must come before any comment, blank line, or instruction. Once a normal comment or instruction appears, later directive-looking lines are treated as ordinary comments. Directives are optional. You need one when you want newer Dockerfile features, such as the cache and secret mounts covered in the last chapter.
Common errors
These mistakes appear often when people start writing Dockerfiles.
- Missing
FROM. Docker reports that no build stage was found. PutFROMfirst, after anyARGor directive. - Misspelled instruction.
COPPYfails with an "unknown instruction" error. The message names the line, so check that line first. - Inline comment in arguments. A trailing
# notecan become part of a value. Put comments on their own lines. - Single quotes in exec form. Docker silently treats the line as shell form. Use double quotes.
- Continuation with trailing whitespace. A space after the backslash prevents the line from continuing. Make sure the backslash is the last character on the line.
- Cleanup in a separate
RUN. Deleting files in a later layer does not shrink the image. Combine install and cleanup in oneRUN.
Check your understanding
Exercise
A Dockerfile contains the line CMD ['node', 'server.js']. The container fails to start with a "not found" style error. What is wrong, and how do you fix it?
Show answer
Exec form must be valid JSON, which requires double quotes. With single quotes, Docker treats the line as shell form and runs it through /bin/sh -c, which tries to execute the text as a shell command. Fix it by using double quotes: CMD ["node", "server.js"].
Exercise
You write RUN apt-get update, then on the next line RUN apt-get install -y curl, then RUN rm -rf /var/lib/apt/lists/*. Why does the image stay large, and how do you restructure it?
Show answer
Each RUN creates its own layer. The package index files are written in the first layer, so deleting them in the third layer hides them but does not remove them from the earlier layer. Combine the commands in one RUN using && and backslash continuations, so the cleanup happens before the layer is saved.
Exercise
Which of these instructions can appear before FROM in a Dockerfile, and why?
Show answer
ARG can appear before FROM, and so can a parser directive or ordinary comments. ARG before FROM lets you parameterize the base image, for example the tag. Every other instruction needs a base image to act on, so it must come after FROM.