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
- How do you secure Docker containers and images?
- What are multi-stage builds, and why use them?
- What is a container, and how does it differ from a virtual machine?
- How does Docker build caching work, and how do you order a Dockerfile to use it well?
- What are Dockerfile best practices for production images?
- ARG or ENV: what is the difference, and how do you pass secrets into a build safely?
- CMD or ENTRYPOINT: what is the difference, and what are exec and shell forms?
- How do you make Docker images smaller?