Layers and cache
- Docker & Kubernetes course
- Beginner
- Lesson 28/82
- 4 min
Learn about image layers and build cache.
Layers and the cache
Each instruction produces a layer and Docker caches the layers. If an instruction and its inputs (the copied files) didn't change, the layer comes from the cache (CACHED). When a layer changes, all layers after it are rebuilt:
=> CACHED [2/5] WORKDIR /app
=> CACHED [3/5] COPY requirements.txt .
=> CACHED [4/5] RUN pip install -r requirements.txt
=> [5/5] COPY . . # only the code changedTurning off the cache
Sometimes the cache isn't wanted: when steps depending on an outside source like RUN apt-get update come from the cache, old packages can remain. --no-cache rebuilds all layers; --pull downloads a newer base image:
docker build --no-cache -t api:1.0 .
docker build --pull -t api:1.0 .
docker history api:1.0 # shows the layers and their sizesPractice Clean build and layers
Write two commands: build api:1.1 without the cache and pulling the newest base image; then show this image's layer history.
Starter code
# buraya yazSample solution
docker build --no-cache --pull -t api:1.1 .
docker history api:1.1Expected output
[+] Building 6.3s (10/10) FINISHED => naming to docker.io/library/api:1.1 done IMAGE CREATED CREATED BY SIZE 4f1e2d3c4b5a 3 seconds ago CMD ["python" "app.py"] 0B <missing> 3 seconds ago RUN pip install --no-cache-dir … 41.2MB
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if COPY . . is written before pip install?
- The packages are reinstalled on every code change Correct answer
- The build fails
- The image shrinks
- The cache works better
Explanation: Everything after the changed layer runs again.
2 Build without using the cache.
docker build ____ -t api:1.0 .
docker build --no-cache -t api:1.0 .
Explanation: --no-cache rebuilds every layer.
3 Match.
| Term | Meaning |
|---|---|
CACHED |
Came from the cache |
--no-cache |
Rebuild all layers |
--pull |
Update the base image |
docker history |
Layer list |