Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 111 ยท Dockerfiles

Build Context and .dockerignore

Understand the Docker build context, why COPY can only see files inside it, and how a .dockerignore file speeds up builds and keeps secrets out of images.

When you run docker build -t app ., the dot at the end is not decoration. It names the build context: the set of files that Docker packages up and makes available to the build. Every COPY and ADD in your Dockerfile can only reach files inside that set. Everything else on your computer is invisible to the build.

This sounds like a technical detail, but it explains three problems beginners meet sooner or later: a COPY that "cannot find" a file that clearly exists, a build that spends ten seconds "transferring context" before it does anything, and a .env file with passwords that ends up inside an image. The cure for the last two is a small file called .dockerignore.

What the build context is

Docker has a client (the docker command) and a builder (BuildKit, which can run on a different machine or in a VM). The builder cannot see your disk, so the client sends it the files it may use. The path you pass to docker build decides which files those are:

TEXT
  your project folder (the context, "." )
  โ”œโ”€โ”€ Dockerfile
  โ”œโ”€โ”€ src/app.py
  โ”œโ”€โ”€ .env                 <- also part of the context unless ignored
  โ””โ”€โ”€ node_modules/ ...    <- also part of the context unless ignored
           |
           |  docker build .        (client sends the files, minus .dockerignore)
           v
     builder  โ”€โ”€  COPY src/ /app/    only paths inside the context can be named

The context is a folder (or a tar archive, a Git URL, or standard input; see below). Paths in COPY are relative to its root, and you cannot climb out of it with ...

A context you can see

To watch the context at work, make a project with a few ordinary files and one big, useless one:

TEXT
project/
โ”œโ”€โ”€ Dockerfile
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ .env                  SECRET_KEY=abc123
โ”œโ”€โ”€ .env.example
โ”œโ”€โ”€ .git/HEAD
โ”œโ”€โ”€ docs/guide.md
โ”œโ”€โ”€ docs/keep.md
โ”œโ”€โ”€ logs/a.log
โ”œโ”€โ”€ logs/b.log
โ”œโ”€โ”€ node_modules/pkg/big.bin    (20 MB of zeros)
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ app.py
    โ””โ”€โ”€ test_app.py

Our Dockerfile copies everything and lists what arrived:

DOCKERFILE
FROM alpine:3.22
WORKDIR /app
COPY . .
CMD ["find", ".", "-type", "f"]

Build it with the plain progress log (--progress=plain) so you can see the context transfer:

CONSOLE
$ docker build --progress=plain -t ctx:1 .
...
#5 transferring context: 20.01MB 2.6s done
...
$ docker run --rm ctx:1 | sort
./.env
./.env.example
./.git/HEAD
./Dockerfile
./README.md
./docs/guide.md
./docs/keep.md
./logs/a.log
./logs/b.log
./node_modules/pkg/big.bin
./src/app.py
./src/test_app.py

Two things stand out. First, transferring context: 20.01MB: Docker uploaded the 20 MB node_modules file even though the image does not need it, and it took a noticeable 2.6 seconds on every build. Second, ./.env is inside the image. Anyone who can pull the image can read SECRET_KEY=abc123 with docker run or by unpacking the layers. Deleting the file in a later RUN rm would not help, because the earlier layer still contains it (see Layers and the Union Filesystem).

COPY . . copies everything in the context: .env files, private keys, .git history, local test databases. If a file should never be inside an image, make sure it is never in the context. A .dockerignore file is the first line of defence; Managing Secrets covers the rest.

The .dockerignore file

Put a file named .dockerignore at the root of the context. Its patterns name files and folders that the client leaves out of the context. Excluded files cannot be copied, do not travel to the builder, and do not affect the build cache. Here is a typical one:

TEXT
# version control and dependencies
.git
node_modules

# secrets and local config
.env
.env.*
!.env.example

# logs anywhere, tests, docs except the guide
**/*.log
logs
src/test_*.py
docs/*
!docs/guide.md

Dockerfile
.dockerignore

Rebuilding with it:

CONSOLE
$ docker build --progress=plain -t ctx:2 .
...
#3 [internal] load .dockerignore
#3 transferring context: 272B done
...
#4 transferring context: 169B 0.0s done
...
$ docker run --rm ctx:2 | sort
./.env.example
./README.md
./docs/guide.md
./src/app.py

The context shrank from 20.01 MB to 169 bytes, and the image now holds only four files. The secret, the dependencies, the logs and the tests are gone.

Pattern rules

.dockerignore looks like .gitignore but is not identical. Patterns are matched against paths relative to the context root:

Pattern Meaning
node_modules The file or folder with that name at the context root
*.log Files ending in .log in the root only
**/*.log Files ending in .log at any depth
docs/* Everything directly inside docs/
src/test_*.py Wildcards work inside a path segment
!docs/guide.md An exception: include this path even though an earlier line excluded it
# comment A comment (the line must start with #)

Three details trip people up:

  1. *.log does not match subfolders. We tested this: with only *.log in the file, the build excluded the top.log file at the root but logs/a.log and logs/b.log were still copied. Use **/*.log to match at any depth.
  2. Order matters for ! exceptions. The last matching line wins. Put !docs/guide.md after docs/*, as in the example, or the exception has no effect.
  3. Ignoring the Dockerfile is allowed. Docker still sends the Dockerfile and .dockerignore to the builder so it can read them; they are only excluded from COPY. This keeps them out of the image without breaking the build.

Allow-list style

For small projects an allow-list is safer than a block-list: ignore everything, then add back what you need. New files never leak by accident.

TEXT
*
!src/
!requirements.txt
!pyproject.toml

We tried the same idea with a per-Dockerfile ignore file containing * and !src/app.py, and the image contained only /app/src/app.py.

One ignore file per Dockerfile

If you build more than one Dockerfile from the same context, a file named <Dockerfile name>.dockerignore placed next to the Dockerfile takes precedence over the root .dockerignore. With docker build -f Dockerfile.prod ., Docker uses Dockerfile.prod.dockerignore when it exists. This lets the production build ignore test files that the development build needs.

Context size and build speed

The context is uploaded at the start of every build, before any instruction runs. A large context slows each build even when everything is cached, because Docker must still read and hash the files. The usual culprits are:

  • dependency folders (node_modules, vendor, .venv, target)
  • version control (.git can be hundreds of megabytes)
  • build output (dist, build, compiled binaries)
  • logs, databases, IDE folders and OS files (.idea, .vscode, .DS_Store)
  • large data or media you mount at run time instead

A good habit is to start every project with a .dockerignore that lists .git, your dependency folder and your .env files, and to watch the transferring context line in the first build. If it says more than a few megabytes, find out why.

Ignoring a dependency folder does not mean the image lacks those packages. The Dockerfile installs them with RUN npm ci or RUN pip install, which gives clean, reproducible results for the image's operating system. Copying your host's node_modules (built for Windows or macOS) into a Linux image is usually a bug.

Other kinds of context

The context does not have to be a local folder:

Terminal
# a folder (the usual case)
docker build -t app .

# a different folder; the Dockerfile is looked up inside it
docker build -t app ./services/api

# a Dockerfile from somewhere else, with the context in the current folder
docker build -f ../shared/Dockerfile.base -t app .

# read-only examples: a Git repository (the builder clones it) and a tarball URL
docker build -t app https://github.com/example/project.git#main
docker build -t app https://example.com/project.tar.gz

You can also pipe a Dockerfile in on standard input. The context is then empty, so COPY of local files fails:

CONSOLE
$ printf 'FROM alpine:3.22\nCOPY nope /x\n' | docker build -t demo -
...
ERROR: failed to build: failed to solve: failed to compute cache key: failed to calculate checksum of ref ...: "/nope": not found

Why COPY ../file fails

Because the builder only receives the context, a path that leaves it cannot work. We created a Dockerfile in a sibling folder containing COPY ../ctx/README.md /x. The result:

CONSOLE
ERROR: failed to build: failed to solve: failed to compute cache key: failed to calculate checksum of ref ...: "/ctx/README.md": not found

The .. is resolved inside the context root, so Docker looked for /ctx/README.md and did not find it. The fix is not a cleverer path. Move the context up to a folder that contains both, and point -f at the Dockerfile:

CONSOLE
$ docker build -f services/api/Dockerfile -t api .

Here the context is the repository root, so COPY shared/ /app/shared/ works, and the Dockerfile lives wherever you like. In a monorepo this is the usual layout.

Checking what you send

To find out what a build receives, add a throwaway stage that lists it, as we did above with find, or run docker build --progress=plain and read the transferring context size. If the numbers surprise you, bisect: add patterns to .dockerignore and rebuild until the size drops.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In docker build -t app ./api, what is the build context?

    The path argument is the context root. Docker sends that folder's files to the builder, and COPY can only use paths inside it.
  2. 2. A .dockerignore contains only *.log. Your project has app.log and logs/error.log. What is excluded?

    A pattern without ** matches only at the context root. Use **/*.log to match log files in every folder.
  3. 3. Why is COPY . . with no .dockerignore dangerous in a project that has a .env file?

    COPY . includes every file in the context. Removing the file in a later step does not erase it from the earlier layer.
  4. 4. COPY ../shared/config.json /app/ fails with not found. What is the correct fix?

    The builder only sees the context. Choose a context root that includes every file you need, and select the Dockerfile with -f.
  5. 5. Given these lines in order, which file is part of the context? docs/* then !docs/guide.md

    docs/* excludes everything in docs, and the later !docs/guide.md re-includes that one file. The last matching line wins.

Summary

  • The build context is the folder (or archive/URL) you pass to docker build. The builder receives it, and COPY/ADD can only use files inside it.
  • Large contexts slow every build; watch the transferring context size.
  • COPY . . copies everything in the context, including secrets such as .env. A .dockerignore keeps them out.
  • .dockerignore patterns are relative to the context root: *.log is root-only, **/*.log is recursive, !path re-includes, and the last matching line wins.
  • Use an allow-list (* plus !src/) for strict control, and <Dockerfile>.dockerignore for per-Dockerfile rules.
  • Paths cannot leave the context. For monorepos, make the context the repository root and pick the Dockerfile with -f.

Next: FROM and RUN