Use a .dockerignore File
A .dockerignore file lists files Docker must leave out of the build context. It keeps the build fast, and it keeps secrets out of the image.
A small .dockerignore
Three lines keep junk and secrets out of the build.
.git
.env
__pycache__/Check the context size
The build prints how much context it sent to the daemon. The byte counts depend on the files in the folder.
docker build -t g4-greet:1.0 . 2>&1 | grep "transferring context"Example
docker build -t g4-greet:1.0 . >/dev/null
docker run --rm g4-greet:1.0Key points
- Build context: the folder Docker sends to the daemon for a build.
- .dockerignore works like .gitignore, one pattern per line.
- Leave out big folders, like .git and node_modules, to speed the build.
- Leave out secret files, like .env, so they never enter an image layer.
- A file in .dockerignore cannot be copied by a COPY step.
In this example, a build runs with a .dockerignore file in place. The build sends a small context and still copies greet.py. The greeting proves the ignore file kept the junk out without breaking the build.
Note
A secret copied before .dockerignore existed still sits in an old layer. Rebuild cleanly.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Why does a .env file belong in .dockerignore?