Docker
/Advanced
Layer Optimization
Definition
The architectural practice of intentionally ordering and combining Dockerfile instructions to maximize the use of the Docker Build Cache and minimize the final number of layers.
Explain Like I'm New
Stacking the blocks efficiently. You put the things that NEVER change (like installing Linux) at the bottom. You put the things that ALWAYS change (like your daily source code) at the absolute top. This stops Docker from doing unnecessary work.
Real World Example
Combining `RUN apt-get update` and `RUN apt-get install nginx` into a single line joined by `&&`. This ensures they form one single cached layer, rather than two. If they are separate, the `update` layer might get permanently cached, causing Docker to install dangerously outdated software months later.
Common Use Cases
- •Speeding up CI/CD pipelines
- •Dockerfile best practices
Interview Questions
basic
- If you have 5 separate `RUN` commands in a Dockerfile, how many image layers are created on the hard drive?
intermediate
- Why should you put the `COPY . .` (copy source code) command as close to the bottom of the Dockerfile as possible?