docker build_error ai_generated true

failed to solve: failed to compute cache key: mount /cache: already mounted in build stage

ID: docker/build-cache-mount-conflict

Also available as: JSON · Markdown · 中文
85%Fix Rate
82%Confidence
1Evidence
2024-04-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Docker 25.0.3 active
BuildKit 0.12.5 active

Root Cause

A RUN --mount=type=cache directive in Dockerfile tries to mount the same cache directory twice in the same build stage, causing a conflict.

generic

中文

Dockerfile中的RUN --mount=type=cache指令尝试在同一构建阶段两次挂载相同的缓存目录,导致冲突。

Official Documentation

https://docs.docker.com/build/cache/

Workarounds

  1. 85% success Merge the two RUN commands into one that uses a single --mount=type=cache, or use different mount paths: RUN --mount=type=cache,target=/cache/apt ... && ...
    Merge the two RUN commands into one that uses a single --mount=type=cache, or use different mount paths: RUN --mount=type=cache,target=/cache/apt ... && ...
  2. 80% success Restructure Dockerfile to use separate stages for each cache mount: FROM base AS builder1 with /cache/apt, then FROM base AS builder2 with /cache/pip.
    Restructure Dockerfile to use separate stages for each cache mount: FROM base AS builder1 with /cache/apt, then FROM base AS builder2 with /cache/pip.

中文步骤

  1. 将两个RUN命令合并为一个使用单一--mount=type=cache的指令,或使用不同的挂载路径:RUN --mount=type=cache,target=/cache/apt ... && ...
  2. 重构Dockerfile,为每个缓存挂载使用单独的构建阶段:FROM base AS builder1使用/cache/apt,然后FROM base AS builder2使用/cache/pip。

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Removing all --mount directives without understanding the conflict loses cache benefits and may break the build.

  2. 80% fail

    Using different cache IDs for the same mount path still causes conflict because the path is already mounted.