Docker Tutorial · Building Images · Lesson 9 of 26
The Build Context and .dockerignore
Keep secrets, Git history and local junk out of the build context and out of your images.
The build context
docker build . sends the directory (the context) to the builder. Everything in it can be copied into the
image, and changes to any of it can invalidate COPY . ..
A .dockerignore file excludes paths from the context, just like .gitignore:
.git
node_modules
__pycache__/
*.log
.env
Excluding .env and other secret files matters: a careless COPY . . otherwise bakes them into an image layer,
where anyone who pulls the image can read them.
trap 'docker image rm -f rc-ctx:a rc-ctx:b > /dev/null 2>&1' EXIT
mkdir project && cd project # keep the demo's files apart from the runner's own
mkdir -p src .git && echo "print('app')" > src/app.py && echo "DB_PASSWORD=hunter2" > .env && echo junk > debug.log
printf 'FROM alpine:3.24\nWORKDIR /app\nCOPY . .\nCMD ["ls", "-A"]\n' > Dockerfile
docker build -q -t rc-ctx:a . > /dev/null
echo "without .dockerignore: $(docker run --rm rc-ctx:a | tr '\n' ' ')"
printf '.git\n.env\n*.log\n' > .dockerignore
docker build -q -t rc-ctx:b . > /dev/null
echo "with .dockerignore: $(docker run --rm rc-ctx:b | tr '\n' ' ')"
Output
without .dockerignore: .env .git Dockerfile debug.log src with .dockerignore: .dockerignore Dockerfile src
Run this on your computer — see “Get Started” for setup.
See Build context.
Test yourself
A .env file with passwords was copied into an image. Is deleting it in a later RUN step enough?
YesNo: it still exists in the earlier layer; exclude it with .dockerignore and rotate the secretsOnly if the image is privateYes, if you rebuild
Show answer
Answer: No: it still exists in the earlier layer; exclude it with .dockerignore and rotate the secrets
Layers are immutable; a later deletion only hides the file.