7. Build Context and Cache
Understand what a build can copy and how to keep rebuilds efficient.
Build Context
In docker build -t app:dev ., the final dot selects the current directory as the build context. COPY reads files from that context, unless copying from another build stage.
Create a .dockerignore alongside the Dockerfile:
.git
.env
*.log
node_modules
__pycache__
Keep application source files needed by COPY in the context.
Cache-Friendly Ordering
For an application with a dependency manifest, copy the manifest and install dependencies before copying frequently changed application code. A source-only change can then reuse the dependency installation step.
A multi-stage build uses one stage for build tools and copies the required artifacts into a runtime stage.
Observe the Cache
In the directory from the Dockerfile lesson:
docker build --progress=plain -t docker-course-site:cache .
docker build --progress=plain -t docker-course-site:cache .
Compare the output. Change index.html and build again to see which steps are reused.
Common Mistakes
- Sending large generated folders in the context.
- Copying secrets into an image and deleting them in a later layer.
- Disabling cache for every build instead of understanding invalidation.
Practice
Add a local log file excluded by .dockerignore. Verify that your Dockerfile does not copy it into the image.
Quick Interview Answer
The build context supplies build inputs. Dockerignore reduces those inputs, and stable-to-changing instruction order makes cache reuse more effective.
Previous: 6. Dockerfile Basics | Next: 8. Networking and Ports
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form