Skip to content
Hands-on IT IT Drills

Day 3: Build Context and .dockerignore

Goal: See what really goes to the builder during a build, and use .dockerignore and COPY --exclude to keep .env, .git and node_modules out. · Duration: approx. 60 min · Prerequisite: Day 2

Briefing

  • The build context is the folder (or URL) at the end of docker build. The client sends it to BuildKit; COPY . . can put anything from it into the image.
  • .dockerignore in the root folder of the context filters before anything is transferred. Whatever is listed there, the builder never sees.
  • A Dockerfile may have its own ignore file <Dockerfile>.dockerignore next to it. It replaces the general one; it doesn’t add to it.
  • COPY --exclude filters only a single instruction. The file stays in the context.
 ~/docker-lab/tag03/            .dockerignore            BuildKit
 ┌──────────────────────┐      ┌─────────────┐      ┌──────────────────┐
 │ .env  .git  notes-*  │ ───► │ filter      │ ───► │ context          │
 │ node_modules  *.test │      │ (client)    │      │ COPY / ADD /     │
 └──────────────────────┘      └─────────────┘      │ --mount=type=bind│
                                                    └──────────────────┘

Drill 1: Measure the context size

source ~/docker-lab/setup/env.sh
mkdir -p ~/docker-lab/tag03 && cd ~/docker-lab/tag03
cp -R "$LAB/code/notes/." . && cp -R "$LAB/code/tag02/notes/." .

The second copy lays the state from the end of Day 2 on top – even if you skipped it. Now build the Dockerfile from Day 2 and pay attention to one line:

docker build --progress=plain -t notes-api:tag03 notes-api 2>&1 \
  | grep -E 'load build context|transferring context'

Expected (abbreviated, may vary by version):

#5 [internal] load build context
#5 transferring context: 6.21kB done

That’s everything that went from notes-api/ to the builder: a few kilobytes. Sizes and times in this chapter will differ on your machine; what matters is the ratio.

Save your progress? Sign up for free

Drill 2: Ballast like in a real project

A real project has a Git repository, installed Node packages and test binaries. You recreate that, with placeholders instead of real packages:

git init -q && git add -A
git -c user.name=lab -c [email protected] commit -qm "Tag 3"
mkdir -p notes-web/node_modules/riesig
dd if=/dev/zero of=notes-web/node_modules/riesig/blob bs=1048576 count=50 2>/dev/null
dd if=/dev/zero of=notes-api/notes-api.test bs=1048576 count=10 2>/dev/null
du -sh .git notes-web/node_modules notes-api/notes-api.test

Expected (abbreviated, may vary by version):

 92K    .git
 50M    notes-web/node_modules
 10M    notes-api/notes-api.test

notes-api.test stands for what go test -c produces. Now you need a tool that shows what arrives at the builder from the context. An empty image into which everything is copied, and -o type=local writes its file system into a folder:

cat > Dockerfile.kontext <<'EOF'
# syntax=docker/dockerfile:1
# Copies the complete build context into an empty image.
# With -o type=local,dest=<folder> its file system ends up in a folder.
FROM scratch
COPY . /
EOF
docker build -q -f Dockerfile.kontext -o type=local,dest=/tmp/notes-kontext . >/dev/null
du -sh /tmp/notes-kontext

Expected (abbreviated, may vary by version):

 60M    /tmp/notes-kontext

Why? With the project folder as the context, everything goes along, including 60 MB that no service needs. On every build, over the socket into the Colima VM.

Save your progress? Sign up for free

Drill 3: What ends up in the image

Day 0 announced it: with the project folder as the context, the .env is in there.

ls -A /tmp/notes-kontext
cat /tmp/notes-kontext/.env
ls /tmp/notes-kontext/.git | head -3

Expected:

.env                    .git                    Dockerfile.kontext
.env.example            README.md               notes-api
notes-web               notes-worker
# Lokale Entwicklungswerte – Lab-Werte, niemals produktiv verwenden
NOTES_API_KEY=lab-api-key-123
COMMIT_EDITMSG
HEAD
config

A COPY . . in any Dockerfile that is built with the project folder puts the key and the complete Git history into a layer. And whatever was in a layer stays in there (Day 11).

Security: .git is at least as dangerous as .env. The history often contains secrets that were deleted from the current state long ago.

Save your progress? Sign up for free

Drill 4: The .dockerignore in the project folder

cat > .dockerignore <<'EOF'
# .dockerignore in the project folder – applies when the project folder is the build context
# Secrets: only the template may go along
.env
.env.*
!.env.example
# Version control and operating system
.git
**/.DS_Store
# Dependencies, build results, caches – at any depth
**/node_modules
**/dist
**/.venv
**/__pycache__
**/*.test
# Docs: only the README in the root folder
*.md
!README.md
EOF
rm -rf /tmp/notes-kontext
docker build -q -f Dockerfile.kontext -o type=local,dest=/tmp/notes-kontext . >/dev/null
du -sh /tmp/notes-kontext
ls -A /tmp/notes-kontext
ls notes-web /tmp/notes-kontext/notes-web

Expected (abbreviated, may vary by version):

120K    /tmp/notes-kontext
.dockerignore           Dockerfile.kontext      README.md
.env.example            notes-api               notes-web
notes-worker
notes-web:
node_modules            package-lock.json       package.json    public  server.js
src

/tmp/notes-kontext/notes-web:
package-lock.json       package.json    public          server.js       src

From 60 MB down to just over 100 KB, without .env, without .git, without node_modules. The rules behind it:

Pattern matches doesn’t match
.env ./.env notes-api/.env
**/node_modules node_modules, notes-web/node_modules –
*.md ./README.md notes-api/HANDBUCH.md
!README.md brings ./README.md back –

Patterns are relative to the root folder of the context, following the rules of Go’s filepath.Match plus ** for any number of folders. Leading and trailing / are ignored.

Save your progress? Sign up for free

Drill 5: Order and exceptions

The most important rule: the last matching line wins. You try that out in a small sandbox, with the example from the Docker docs:

mkdir -p /tmp/notes-ign/node_modules /tmp/notes-ign/sub/node_modules
cd /tmp/notes-ign
touch node_modules/x sub/node_modules/y README.md NOTES.md README-secret.md
cat > .dockerignore <<'EOF'
node_modules
*.md
!README*.md
README-secret.md
EOF
rm -rf /tmp/notes-kontext
docker build -q -f ~/docker-lab/tag03/Dockerfile.kontext \
  -o type=local,dest=/tmp/notes-kontext . >/dev/null
du -sh /tmp/notes-kontext
find /tmp/notes-kontext -type f

Expected (order may vary):

4.0K    /tmp/notes-kontext
/tmp/notes-kontext/sub/node_modules/y
/tmp/notes-kontext/README.md
/tmp/notes-kontext/.dockerignore

Two lessons: README-secret.md is missing because the line README-secret.md comes after the exception !README*.md and thus matches last. And node_modules without **/ only matches the folder in the root directory; sub/node_modules slips through. Now reverse the order and add **/:

cat > .dockerignore <<'EOF'
**/node_modules
*.md
README-secret.md
!README*.md
EOF
rm -rf /tmp/notes-kontext
docker build -q -f ~/docker-lab/tag03/Dockerfile.kontext \
  -o type=local,dest=/tmp/notes-kontext . >/dev/null
du -sh /tmp/notes-kontext
find /tmp/notes-kontext -type f
cd ~/docker-lab/tag03

Expected (order may vary):

4.0K    /tmp/notes-kontext
/tmp/notes-kontext/README.md
/tmp/notes-kontext/README-secret.md
/tmp/notes-kontext/.dockerignore

!README*.md now comes last and brings README-secret.md back. If you write an exception at the bottom, you open it up for everything that was excluded before it.

Warning: .dockerignore is not .gitignore. In .gitignore, node_modules matches at any depth; in .dockerignore, only in the root folder. When in doubt, **/.

Save your progress? Sign up for free

Drill 6: The service’s .dockerignore

In this book you build with the service folder as the context. So notes-api/ needs its own .dockerignore. First look at what is in the image under /src today:

docker run --rm --entrypoint ls notes-api:tag03 -A /src

Expected:

Dockerfile
Dockerfile.naiv
go.mod
go.sum
main.go

The image is from Drill 1, before the ballast. With the test binary from Drill 2 it would be 10 MB more. Now the ignore file:

cat > notes-api/.dockerignore <<'EOF'
# notes-api/.dockerignore – applies when notes-api/ is the build context
Dockerfile*
.dockerignore
*.md
.git
.env*
**/*.test
EOF
docker build --progress=plain -t notes-api:tag03 notes-api 2>&1 \
  | grep -E 'transferring context|naming to'
docker run --rm --entrypoint ls notes-api:tag03 -A /src

Expected (abbreviated, may vary by version):

#5 transferring context: 4.93kB done
#9 naming to docker.io/library/notes-api:tag03 done
go.mod
go.sum
main.go

Why does the build work even though Dockerfile* is ignored? The Dockerfile and .dockerignore still go to the builder, because it needs them to build. Only COPY, ADD and bind mounts can no longer get at them. Is the service still running?

docker run -d --name notes-api -p 127.0.0.1:8080:8080 \
  -e NOTES_API_KEY=lab-api-key-123 notes-api:tag03
sleep 3 && curl -s localhost:8080/healthz
docker ps --filter name=notes-api --format '{{.Names}}  {{.Status}}'
docker rm -f notes-api >/dev/null

Expected (abbreviated, may vary by version):

ok
notes-api  Up 3 seconds (healthy)

Save your progress? Sign up for free

Drill 7: One ignore file per Dockerfile

Some Dockerfiles need different rules from the rest. For that you put a file <Dockerfile>.dockerignore next to the Dockerfile. Here as a whitelist: everything out, only notes-api/ back in.

cp Dockerfile.kontext Dockerfile.whitelist
cat > Dockerfile.whitelist.dockerignore <<'EOF'
# Whitelist: first exclude everything, then bring back selectively
*
!notes-api/
# exclude again inside notes-api (last match wins)
notes-api/Dockerfile*
notes-api/**/*.test
EOF
rm -rf /tmp/notes-kontext
docker build -q -f Dockerfile.whitelist \
  -o type=local,dest=/tmp/notes-kontext . >/dev/null
du -sh /tmp/notes-kontext
find /tmp/notes-kontext -type f | sort

Expected (abbreviated, may vary by version):

 20K    /tmp/notes-kontext
/tmp/notes-kontext/notes-api/.dockerignore
/tmp/notes-kontext/notes-api/go.mod
/tmp/notes-kontext/notes-api/go.sum
/tmp/notes-kontext/notes-api/main.go

The project .dockerignore no longer plays any role for this build; the Dockerfile-specific one takes precedence. There is no merging: if the whitelist had no * at the beginning, the .env would be included again. And Dockerfile.whitelist.dockerignore only applies because it is in the same folder as Dockerfile.whitelist.

Tip: Whitelists (* and then !…) are more robust than blacklists. A new file with secrets in the project doesn’t automatically end up in the context.

Save your progress? Sign up for free

Drill 8: COPY --exclude

COPY --exclude has been stable since Dockerfile frontend 1.19; before that, the option was only available in the labs channel. With # syntax=docker/dockerfile:1 you get the current 1.x version and thus --exclude.

cat > Dockerfile.exclude <<'EOF'
# syntax=docker/dockerfile:1
# COPY --exclude filters only this one instruction, not the build context.
FROM scratch
COPY --exclude=*.md --exclude=notes-worker/uv.lock . /
EOF
rm -rf /tmp/notes-kontext
docker build -q -f Dockerfile.exclude -o type=local,dest=/tmp/notes-kontext . >/dev/null
du -sh /tmp/notes-kontext
ls /tmp/notes-kontext /tmp/notes-kontext/notes-worker
docker build --progress=plain -f Dockerfile.exclude -o type=local,dest=/tmp/x . 2>&1 \
  | grep 'transferring context'
rm -rf /tmp/x

Expected (abbreviated, may vary by version):

112K    /tmp/notes-kontext
/tmp/notes-kontext:
Dockerfile.exclude      Dockerfile.whitelist.dockerignore       notes-web
Dockerfile.kontext      notes-api                               notes-worker
Dockerfile.whitelist

/tmp/notes-kontext/notes-worker:
pyproject.toml  src
#4 transferring context: 71.30kB done

README.md and uv.lock are missing from the result, but transferring context shows: they were transferred. A second COPY without --exclude or a bind mount could get at them. Excluding secrets is therefore the job of .dockerignore; --exclude is a tool for multi-stage builds, when one stage should copy less than another (from Day 5 on).

Tip: The context doesn’t have to be a local folder. docker build also accepts a Git repository or a tarball via URL; the builder then clones or unpacks it itself. The .dockerignore in the root folder applies there too. In this book we stick to local folders.

Save your progress? Sign up for free

Checkpoint

What arrives at the builder with the project .dockerignore?

cd ~/docker-lab/tag03
rm -rf /tmp/notes-kontext
docker build -q -f Dockerfile.kontext -o type=local,dest=/tmp/notes-kontext . >/dev/null
ls -A /tmp/notes-kontext

Expected: no .env, no .git, but .env.example.

.dockerignore
.env.example
Dockerfile.exclude
Dockerfile.kontext
Dockerfile.whitelist
Dockerfile.whitelist.dockerignore
README.md
notes-api
notes-web
notes-worker

In the image, /src contains only the Go files:

docker run --rm --entrypoint ls notes-api:tag03 /src

Expected:

go.mod
go.sum
main.go

Challenge

Without a Dockerfile on disk, show what arrives at the builder from the context – once with the project .dockerignore, once without. Which traps (.env, .git, node_modules, *.test) are in there each time?

Hint: docker build -f - reads the Dockerfile from stdin; the context remains the specified folder along with its .dockerignore.

Solution

A two-line Dockerfile via printf on stdin; the context is the project folder:

cd ~/docker-lab/tag03
rm -rf /tmp/ctx
printf 'FROM scratch\nCOPY . /\n' \
  | docker build -q -f - -o type=local,dest=/tmp/ctx . >/dev/null
find /tmp/ctx -name '.env' -o -name .git -o -name node_modules -o -name '*.test'

Expected: no output; none of it is in the context. Now without the ignore file:

mv .dockerignore .dockerignore.aus
rm -rf /tmp/ctx
printf 'FROM scratch\nCOPY . /\n' \
  | docker build -q -f - -o type=local,dest=/tmp/ctx . >/dev/null
find /tmp/ctx -name '.env' -o -name .git -o -name node_modules -o -name '*.test'
mv .dockerignore.aus .dockerignore

Expected:

/tmp/ctx/notes-web/node_modules
/tmp/ctx/notes-api/notes-api.test
/tmp/ctx/.git
/tmp/ctx/.env

All four traps would be in the context without .dockerignore. You can put this build without a Dockerfile in front of every real build in CI. Finally, clean up:

rm -rf /tmp/notes-kontext /tmp/notes-ign /tmp/ctx
docker ps -a --filter name=^notes- --format '{{.Names}}' | xargs -r docker rm -f
docker image ls --format '{{.Repository}}:{{.Tag}}' \
  | grep -E '^(notes-|localhost:5001/)' | xargs -r docker rmi
docker buildx prune --builder docker-lab --all --force

Save your progress? Sign up for free

Enterprise Note

  • .dockerignore belongs in the repository and in every code review. One line too few lets secrets into the context; one too many breaks the build with COPY failed (Day 15).
  • In monorepos, prefer building per service or using whitelist ignore files per Dockerfile instead of transferring the root folder with gigabytes of dependencies.
  • CI runners check out the repository with .git. Without .git in .dockerignore, the history ends up in the image as soon as there is a COPY . . anywhere.
  • Remote contexts (Git URL) are handy, but check the origin and ref: a branch name is movable, a commit SHA is not.
  • Secret scanners such as trivy image --scanners secret (Day 11) find leaks in the image; the filter in .dockerignore prevents them. You need both.