🐳 Docker Beginner

What are Docker image layers?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Docker development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

Docker images are built from a series of read-only layers, where each layer represents a set of filesystem changes created by a Dockerfile instruction (RUN, COPY, ADD). Layers are stacked on top of each other using a union filesystem (overlay2 is the default storage driver on modern Linux). Each layer stores only the changes (diff) from the previous layer — only files added, modified, or deleted. When you run a container, Docker adds a thin writable layer (container layer) on top — all writes go there; the image layers remain read-only. Layer caching: Docker caches each layer by its instruction + content. When rebuilding, if an instruction and its dependencies haven't changed, Docker reuses the cached layer — making rebuilds fast. Cache is invalidated from the changed instruction downward. Implication for Dockerfile ordering: put instructions that change frequently (COPY source code, ENV) at the end; put instructions that change rarely (installing dependencies) early. Example: COPY package.json first → npm install → COPY rest of source code. This way, npm install is cached if only source changed. Viewing layers: docker image history myapp:1.0 or docker inspect myapp:1.0. Sharing layers: if two images share layers (e.g., same base image), Docker stores the shared layers only once on disk.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Docker project.