backend / docker / 04_docker_image_layers.md

Docker Image Layers

3 interview angles 2 min read source

Docker Image Layers

A Docker image is built in layers, each representing an instruction in the Dockerfile. These layers form a stacked file system, making images more efficient and easier to manage.

1. What Is a Docker Image Layer?

  • Each command in a Dockerfile (like RUN, COPY, or ADD) creates a new layer.
  • Layers are cached and immutable. If the command doesn’t change, Docker uses the cached layer.
  • Layers are stacked on top of each other to form the final image.

2. Why Are Layers Important?

Efficiency

  • Layers are reused across images. This saves bandwidth and storage.
  • Only changed layers are rebuilt, making builds faster.

Version Control

  • Since each layer is based on the previous one, it’s easy to roll back changes.

Separation of Concerns

  • You can structure Dockerfiles to separate dependencies, application code, and configuration, improving maintainability.

3. Layer Caching Example

Consider this Dockerfile:

FROM python:3.14
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]

Each instruction creates a layer:

  1. FROM – Base Python image
  2. WORKDIR – Sets working directory
  3. COPY requirements.txt – Adds requirements file
  4. RUN pip install – Installs dependencies
  5. COPY . . – Adds source code
  6. CMD – Default command to run

If you only change your source code, Docker will reuse layers 1 to 4 and only rebuild the last two.


4. Best Practices for Layer Management

  • Order matters: Place the least changing instructions early to maximize caching.
  • Minimize layers: Combine related commands using && to reduce image size.
  • Clean up: Remove temporary files in the same layer where they’re created to avoid bloating the image.
RUN apt-get update && apt-get install -y \
    some-package \
 && rm -rf /var/lib/apt/lists/*

Summary

  • Docker images are made up of layers.
  • Layers provide reusability, faster builds, and version control.
  • Effective layer management improves performance and reduces image size.

Interview angle

  • “How do you make builds fast?” - order instructions from least to most frequently changing. Copy the dependency manifest and install dependencies before copying source, so a code change doesn’t invalidate the dependency layer. That single ordering is most of the win.
  • “Why doesn’t deleting a file in a later layer shrink the image?” - layers are additive; a deletion just masks the file in the union filesystem while the bytes remain in the earlier layer. Secrets removed this way are still extractable - use multi-stage builds or build secrets instead.
  • “How do you reduce image size?” - multi-stage builds so build tooling never reaches the final image, a slim or distroless base, combining RUN steps that create and clean up in one layer, and a .dockerignore so build context stays small.