A development team builds a Python microservice with this Dockerfile:
FROM python:3.12-slim
WORKDIR /srv/app
RUN apt-get update && apt-get install -y build-essential
COPY . /srv/app
RUN pip install --no-cache-dir -r requirements.txt
ENTRYPOINT ["python", "main.py"]
When a single .py file is modified and docker build is re-run, the dependency-installation step executes again, adding several minutes to the build even though requirements.txt has not changed. Considering how image layers and the build cache behave, which revision will most effectively keep the dependency-installation layer cached so that only the application-code layer is rebuilt?
Copy requirements.txt in an earlier layer, run pip install -r requirements.txt, then copy the remainder of the application files.
Combine the apt-get and pip install commands into a single RUN instruction so they live in one layer.
Invoke docker build --pull to refresh the base image before every build.
Replace the ENTRYPOINT instruction with a CMD instruction to improve build caching.
Docker creates a new read-only layer for every instruction in a Dockerfile and reuses a cached layer only when the instruction and its inputs are unchanged. The COPY . /srv/app instruction copies every source file; changing any file changes that layer's checksum, which invalidates it and every layer that follows, including the time-consuming pip install layer. By copying only requirements.txt first, running pip install, and then copying the rest of the source, the expensive dependency layer depends on a file that seldom changes, so it remains in the cache on most rebuilds. Merging commands, refreshing the base image, or switching ENTRYPOINT/CMD do not stop the cache bust caused by the wide COPY . layer.
Ask Bash
Bash is our AI bot, trained to help you pass your exam. AI Generated Content may display inaccurate information, always double-check anything important.
What are Docker image layers?
Open an interactive chat with Bash
Why does copying only the requirements.txt file into a separate layer improve build caching?
Open an interactive chat with Bash
How does the order of Dockerfile instructions affect the build process?
Open an interactive chat with Bash
CompTIA Linux+ XK0-006 (V8)
Services and User Management
Your Score:
Report Issue
Bash, the Crucial Exams Chat Bot
AI Bot
Loading...
Loading...
Loading...
IT & Cybersecurity Package Join Premium for Full Access