Docker interview question · Most asked

What is the difference between an image and a container, and how do image layers work?

Summary

An image is a read-only template: an ordered stack of filesystem layers plus metadata (entrypoint, environment, exposed ports). A container is a running (or stopped) instance of an image with a thin writable layer on top. Layers are content-addressed and shared between images, so pulling and storing many images that share a base is efficient.

Longer Answer

Each filesystem-changing Dockerfile instruction (RUN, COPY, ADD) creates a layer. The storage driver (overlay2 on most Linux hosts) presents the layers as one filesystem using a union mount; changes made by the container go to its writable layer with copy-on-write and disappear when the container is removed (persistent data belongs in volumes).

Because layers are immutable, deleting a file in a later layer does not shrink the image: the bytes remain in the earlier layer. That is why cleanup must happen in the same RUN instruction that created the files, or in a multi-stage build.

Key Points

  • Image = read-only layers + metadata.
  • Container = image + writable layer.
  • Layers shared and content-addressed.
  • Deleting in a later layer does not shrink the image.

More most-asked Docker questions

← All Docker questions