Technical Mid Level

How do Docker image layers work? How do you optimise a Dockerfile to produce smaller images with better layer caching?

Quick Tip

Show the caching strategy: "I COPY package.json and install dependencies before copying application code. That way, code changes do not invalidate the dependency cache. Multi-stage builds keep the final image free of build tools."

What good answers include

Each Dockerfile instruction creates a layer. Layers are cached and reused — if a layer has not changed, Docker skips rebuilding it and everything above. Optimisation: order instructions from least to most frequently changing (COPY package.json before COPY . so dependency install is cached), combine RUN commands to reduce layers, use multi-stage builds to separate build-time dependencies from the runtime image, use specific base image tags (not latest), and clean up in the same RUN command (apt-get install && rm -rf /var/lib/apt/lists/*). Strong candidates discuss: the union filesystem (overlay2), why each COPY invalidates subsequent layers, using .dockerignore to exclude unnecessary files, and choosing slim or alpine base images.

What interviewers are looking for

Core Docker optimisation skill. Candidates who write naive Dockerfiles with no layer ordering produce slow builds and bloated images. Those who understand the layer cache and use multi-stage builds create efficient CI pipelines.

← All Docker questions