Sub topic 2
Dockerfile instructions and the build context
This chapter assumes you can run containers with docker run, can read a short Dockerfile, and have built a small app in Go, Node.js or Python. It covers the instructions you will use in every Dockerfile in this tutorial. It also covers the build context, the set of files a build can see. Most "file not found" errors during COPY come from misunderstanding the context.
What a Dockerfile is
A Dockerfile is a text file of instructions that the builder runs from top to bottom to produce an image. Each instruction is a keyword in capitals followed by arguments. Lines starting with # are comments. The first instruction is normally FROM, which sets the base image the rest of the file builds on.
The previous chapter explained that instructions which change the filesystem create layers. Here the focus is on what each instruction does and where it is easy to get it wrong.
The core instructions
| Instruction | Purpose | Runs at |
|---|---|---|
| `FROM` | Choose the base image and start a build stage | Build |
| `WORKDIR` | Set the working directory for later instructions | Build and run |
| `COPY` | Copy files from the build context into the image | Build |
| `RUN` | Execute a command and keep the filesystem changes | Build |
| `ENV` | Set an environment variable | Build and run |
| `ARG` | Define a build-time variable | Build only |
| `EXPOSE` | Document a listening port | Metadata only |
| `USER` | Set the user for later instructions and the container | Build and run |
| `CMD` | Default command for the container | Run |
| `ENTRYPOINT` | Fixed executable for the container | Run |
Here is a small Dockerfile that uses most of them. It assumes a Node.js project with a package.json, a package-lock.json and an index.js that listens on port 3000.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", "index.js"]FROM
FROM node:20-slim pulls the named image and uses it as the starting filesystem. A Dockerfile can contain several FROM lines. Each one starts a new stage, which is the basis of multi-stage builds. A later chapter covers that in detail. For now, remember that every FROM resets the state: variables, working directory and user from an earlier stage do not carry over.
WORKDIR
WORKDIR /app creates the directory if it does not exist and makes it the current directory for every later RUN, COPY, CMD and ENTRYPOINT. It also becomes the default directory of the running container. Use it instead of RUN cd /app, because a cd inside one RUN does not affect the next instruction.
Relative paths in COPY destinations resolve against the current WORKDIR. In the example, ./ means /app/.
COPY and ADD
COPY <src> <dest> copies files from the build context into the image. The source paths are relative to the context root, not to the Dockerfile.
Three rules cause most mistakes:
- With more than one source, or a wildcard that may match several files, the destination must end in
/. - Copying a directory copies its contents, not the directory itself.
COPY src /app/puts the files fromsrcdirectly in/app/. - You cannot copy from outside the context.
COPY ../config.yml .fails.
ADD does the same job and two more: it extracts local tar archives, and it can download from a URL. That extra behavior is easy to trigger by accident. Use COPY unless you specifically need automatic extraction.
RUN
RUN executes a command in the image and commits the resulting filesystem changes as a layer. It has two forms:
# Shell form: runs through /bin/sh -c
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
# Exec form: runs the program directly, no shell
RUN ["/bin/echo", "hello"]Shell form is the usual choice for RUN because you often need &&, pipes or variable expansion. Chaining the install and the cleanup in a single RUN matters. If you delete the package lists in a separate RUN, the earlier layer still contains them and the image does not shrink.
ENV and ARG
ENV NODE_ENV=production sets a variable that exists during the build after that line and in every container started from the image. ARG defines a variable that exists only during the build, and you set it with --build-arg:
FROM alpine:3.20
ARG APP_VERSION=dev
RUN echo "building $APP_VERSION" > /version.txtdocker build --build-arg APP_VERSION=1.4.2 -t versioned .Two gotchas apply here:
- An
ARGdeclared beforeFROMis available only toFROMlines. To use it inside a stage, declare it again afterFROM. - Build arguments are not secret. Their values appear in
docker history. Never pass passwords or tokens this way. A later chapter covers the safe alternative.
EXPOSE
EXPOSE 3000 records that the app listens on port 3000. It does not publish the port. You still need docker run -p 8080:3000 to reach it from the host. Treat it as documentation.
USER
USER switches the user for the instructions that follow and for the running container. It is covered fully in a later chapter. Note for now that the base image decides which users exist. The official Node images include a node user, and many images offer only root.
CMD and ENTRYPOINT
Both define what runs when the container starts, and both have a shell form and an exec form. Prefer the exec form, which is a JSON array with double quotes:
CMD ["node", "index.js"]The shell form, CMD node index.js, wraps the command in /bin/sh -c. The shell becomes the container's main process, and it may not forward the stop signal that docker stop sends. The app then gets killed after the timeout instead of shutting down cleanly. Exec form avoids that.
Together, the two instructions work like this:
ENTRYPOINTis the fixed program. Arguments fromdocker run image argsare appended to it.CMDprovides default arguments, or a default command if there is noENTRYPOINT. Arguments given todocker runreplace it.- Only the last
CMDand the lastENTRYPOINTin a stage take effect.
FROM alpine:3.20
ENTRYPOINT ["echo", "Hello,"]
CMD ["world"]Running the image with no arguments prints Hello, world. Running it with docker run greeter Kiro prints Hello, Kiro.
The build context
When you run docker build, you pass a context argument, usually a dot:
docker build -t myapp .The context is the directory the builder is allowed to read. Every COPY source is resolved inside it. The Dockerfile is found at ./Dockerfile by default, but it does not have to be in the context root.
docker build -f docker/Dockerfile.prod -t myapp:prod .Here the context is still ., so COPY . . copies the whole project, even though the Dockerfile lives in docker/.
Why the context size matters
With a local directory, the client makes the context available to the builder, which may be a daemon on another machine or in a VM. Docker Desktop and remote builders both work this way. If your directory holds a 2 GB node_modules folder, or a .git history, the builder may have to receive it before your first instruction runs. BuildKit, the default builder in current Docker, transfers only files that instructions actually need. Even so, COPY . . pulls in everything the context exposes, and any change to those files invalidates the cache for that step. A .dockerignore file, covered in a later chapter, removes files from the context before any of this happens.
Other kinds of context
The context does not have to be a local directory:
- A Git URL such as
docker build https://github.com/example/repo.git#mainclones the repository and uses it as the context. - A tar archive URL is downloaded and unpacked.
- Reading the Dockerfile from standard input, as in
docker build -t test - < Dockerfile, gives you no context. AnyCOPYof a local file fails, butRUNandFROMwork.
Common errors
| Symptom | Likely cause |
|---|---|
| `COPY failed: file not found in build context` | The path is wrong relative to the context root, or `.dockerignore` excludes it |
| `forbidden path outside the build context` | The source uses `..` or points outside the context |
| Container ignores `docker stop` for ten seconds | The shell form of `CMD` made `sh` the main process |
| `$VAR` is empty inside the stage | `ARG` was declared before `FROM` and not repeated in the stage |
| Image does not shrink after a cleanup step | The deleted files are still in an earlier layer |
Exercise
A project has the layout app/Dockerfile and app/src/main.py, and you run docker build -f app/Dockerfile -t demo app. Which path do you write in the Dockerfile to copy main.py, and why does COPY ../shared/util.py . fail?
Show answer
Write COPY src/main.py .. The context is the app directory because it is the last argument to docker build, and COPY sources are relative to the context root. ../shared/util.py points outside the context, so the builder refuses it. To use shared, make the parent directory the context and set the Dockerfile with -f.
Exercise
What does docker run image start do if the image has ENTRYPOINT ["echo", "Hello,"] and CMD ["world"]?
Show answer
It prints Hello, start. The argument given to docker run replaces CMD, and the result is appended to the fixed ENTRYPOINT.