Docker "max depth exceeded" - Too Many Image Layers in CI
Docker images are stacks of layers, and the storage driver caps how deep that stack can go (overlay2 allows up to 128). An image built by piling on a great many RUN/COPY steps - or repeatedly committing onto an already-deep base - hits "max depth exceeded".
What this error means
A build or pull fails with max depth exceeded, naming the storage driver. The image has accumulated more layers than the driver permits, so it cannot be built or unpacked.
failed to create layer: max depth exceeded
# overlay2 caps the layer stack (128); this image has too many stacked layersCommon causes
Too many RUN/COPY/ADD steps
Each RUN/COPY/ADD adds a layer. A Dockerfile (or generated one) with hundreds of separate steps can exceed the driver’s depth limit.
Repeatedly committing onto a deep base
Building a new image FROM an already-deep image, repeatedly (a chain of derived images, or docker commit loops), keeps stacking layers until the cap is hit.
How to fix it
Collapse steps to reduce layer count
Combine related commands into single RUN layers and copy in fewer steps.
# instead of many separate RUNs:
RUN apt-get update && apt-get install -y curl git \
&& rm -rf /var/lib/apt/lists/*Flatten or rebase a deep image
Use multi-stage builds to copy only final artifacts into a shallow final stage, or flatten a deep base.
FROM build AS final-src
FROM debian:12-slim
COPY --from=final-src /app /app # one COPY, shallow final imageHow to prevent it
- Combine related commands into fewer RUN layers.
- Use multi-stage builds so the final image stays shallow.
- Avoid long chains of derived images that keep stacking layers.