Sub topic 5
Setting up the filesystem: WORKDIR, COPY, and RUN
This chapter assumes you can read a basic Dockerfile, know that an image is built from a base image with FROM, and understand what a build context is. Here you will learn the three instructions that shape the filesystem inside the image: WORKDIR, COPY, and RUN. You will also learn the mistakes that cause most surprises with them.
How the three instructions fit together
After FROM gives you a base filesystem, you usually need to do three things:
- Choose where your application lives (
WORKDIR). - Bring files from the build context into the image (
COPY). - Execute commands at build time that install or generate more files (
RUN).
Each of these produces a new layer, or in the case of WORKDIR, a change to image metadata that later instructions rely on. The order you choose affects correctness and build speed.
WORKDIR: set the working directory
WORKDIR sets the directory that later RUN, COPY, CMD, and ENTRYPOINT instructions use as their current directory. If the directory does not exist, Docker creates it.
FROM node:20-slim
WORKDIR /appWithout WORKDIR, you would work in /, the root of the filesystem. Copying your app there mixes it with system directories such as /etc and /usr.
Why not `RUN cd`?
A common mistake is to change directory inside a RUN instruction:
FROM debian:12-slim
RUN mkdir /app && cd /app
RUN pwdThe second RUN prints /, not /app. Each RUN starts a fresh shell, so a cd only lasts until the end of its own instruction. WORKDIR persists across instructions, so use it instead.
Relative paths and multiple uses
You can use WORKDIR more than once. A relative path is resolved against the previous WORKDIR:
FROM debian:12-slim
WORKDIR /srv
WORKDIR app
WORKDIR config
RUN pwdThe final RUN pwd prints /srv/app/config. This is legal, but easy to misread. Prefer absolute paths so each line says what it means.
WORKDIR can also expand variables that you set earlier with ENV. You will meet ENV in the next chapter.
COPY: bring files into the image
COPY copies files or directories from the build context into the image. The form is:
COPY <source> <destination>Sources are paths relative to the build context. The destination is a path inside the image. If the destination is relative, it is resolved against the current WORKDIR.
FROM node:20-slim
WORKDIR /app
COPY package.json ./
COPY src/ ./src/Here ./ means /app/, and ./src/ means /app/src/.
Trailing slashes matter
The trailing slash on the destination tells Docker whether the destination is a directory:
COPY package.json ./places the file at/app/package.json.COPY package.json /app/configwith no trailing slash creates a file namedconfig, unless/app/configalready exists as a directory.
When you copy several sources, the destination must be a directory and should end in /.
Copying a directory copies its contents
COPY src/ ./src/ copies what is inside src, not a folder called src placed inside the destination. This is why you often repeat the directory name in the destination. If you wrote COPY src/ ./, the files from src would land directly in /app, mixed with everything else.
Wildcards
COPY accepts wildcards in the source. The first example in the Topic Spine uses one:
COPY package*.json ./This matches both package.json and package-lock.json. If no file matches a wildcard, the build fails. That is useful because a missing lock file is caught early.
Copying everything
COPY . . copies the entire build context into the working directory. It is convenient, but it copies whatever is in the context, including files you did not mean to ship. A .dockerignore file limits this, and a later chapter covers it. Place COPY . . after your dependency installation so that source edits do not invalidate the dependency layer.
Ownership and permissions
Files copied with COPY are owned by root by default, no matter who owns them on your machine. If the container later runs as an unprivileged user, that user may be unable to write to those files. Use --chown to set ownership during the copy:
COPY --chown=node:node . .This is cheaper than running chown -R in a separate RUN, which would duplicate every changed file into a new layer. You can also set permissions with --chmod, for example COPY --chmod=755 entrypoint.sh /usr/local/bin/. The user chapter returns to this.
COPY versus ADD
ADD looks similar but also extracts local tar archives and can fetch URLs. Those extra behaviors make it less predictable. Use COPY unless you specifically need archive extraction.
RUN: execute commands at build time
RUN executes a command in the image as it exists at that step, then saves the resulting filesystem changes as a new layer. Use it to install packages, compile code, and create directories.
RUN npm ci --omit=devShell form and exec form
RUN has two forms:
| Form | Example | How it runs |
|---|---|---|
| Shell form | `RUN apt-get update && apt-get install -y curl` | Through `/bin/sh -c`, so pipes, `&&`, and variable expansion work |
| Exec form | `RUN ["/bin/bash", "-c", "echo hello"]` | Runs the program directly, with no shell processing |
For RUN, shell form is the normal choice, because you usually want && and similar features. The choice matters more for CMD and ENTRYPOINT, covered in a later chapter.
Combine related commands into one RUN
Each RUN creates a layer. Files deleted in a later layer still take up space in the earlier one, because layers only add changes. This is a common way to bloat an image:
FROM debian:12-slim
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*The package index is stored in the first layer, so the rm in the third layer hides it but does not shrink the image. Combine the commands so the cleanup happens in the same layer:
FROM debian:12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*Combining apt-get update with apt-get install has a second benefit. If they were separate, the build cache could reuse an old update layer and then install stale package versions.
Failures and pipes
A RUN instruction fails the build when its command exits with a non-zero status. With a pipe, however, the shell reports only the exit status of the last command:
RUN curl -fsSL https://example.com/setup.sh | shIf curl fails, sh may still receive empty input and succeed. To make the pipeline fail when any part fails, use a shell with pipefail:
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN curl -fsSL https://example.com/setup.sh | shSHELL changes the shell that shell-form instructions use. The base image must include bash, which debian images do and alpine images do not.
Putting it together
This Dockerfile uses all three instructions in the order that works well for a Node.js application:
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .Reading it top to bottom:
WORKDIR /appcreates/appand makes it the current directory.COPY package*.json ./brings in only the dependency manifests.RUN npm ci --omit=devinstalls production dependencies into/app/node_modules.COPY . .brings in the rest of the source.
Splitting the copy into two steps lets Docker reuse the npm ci layer when only source files change. The chapter on layers and caching explains the mechanism.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `COPY failed: file not found in build context` | The source path is outside the context, or `.dockerignore` excludes it | Check the path relative to the context root and review `.dockerignore` |
| `RUN cd` has no effect on later commands | Each `RUN` starts a new shell | Use `WORKDIR` |
| App cannot write files at runtime | Files are owned by `root` but the container runs as another user | Use `COPY --chown` |
| Image is larger than expected after deleting files | The deleted files live in an earlier layer | Delete in the same `RUN` that created them |
| `COPY ../config .` fails | Sources cannot reach above the build context root | Move the file into the context, or change the context directory |
Exercise
A Dockerfile contains RUN cd /app followed by COPY . . and RUN npm ci. The author expects the files to land in /app. Where do they land, and how do you fix it?
Show answer
They land in /, the default working directory, because cd only affects the shell of its own RUN instruction. Replace RUN cd /app with WORKDIR /app, which persists for all later instructions. The npm ci will then also run in /app.
Exercise
You install a build tool in one RUN instruction and delete its download cache in the next RUN. The image is still large. Why, and what do you change?
Show answer
Each RUN creates its own layer, and layers only add changes. The cache files remain stored in the first layer, so the later delete only hides them. Put the install and the cleanup in the same RUN instruction, joined with &&, so the files never appear in a saved layer.