What is a Docker image, and how do layers work?
basicAn image is an immutable, read-only stack of filesystem layers plus metadata (entrypoint, env, ports). Each Dockerfile instruction that changes the filesystem (RUN, COPY, ADD) creates a layer identified by a content hash; a container adds a thin writable layer on top.
- Layers are shared between images and cached by the builder: if an instruction and everything before it is unchanged, the cached layer is reused.
- Once a layer is invalidated, all layers after it are rebuilt.
- Deleting a file in a later layer does not shrink the image; the bytes still exist in the earlier layer.
- Does
RUN rm bigfilein a later step reduce image size? No, the file stays in the earlier layer; remove it in the sameRUNor use a multi-stage build. - Do
ENV/CMDcreate layers with data? They create metadata-only (empty) layers.