docker build_error ai_generated true

警告:环境变量 'GIT_COMMIT' 的更改使构建缓存失效。

WARNING: Build cache was invalidated by environment variable 'GIT_COMMIT' change.

ID: docker/build-cache-invalidation-due-to-env

其他格式: JSON · Markdown 中文 · English
85%修复率
82%置信度
1证据数
2024-03-05首次发现

版本兼容性

版本状态引入弃用备注
Docker 24.0.6 active
Docker 25.0.2 active

根因分析

Docker 构建使用带有动态变量(例如 git 提交哈希)的 --build-arg,该变量每次构建都会更改,导致所有后续层被重建。

English

Docker build uses --build-arg with a dynamic variable (e.g., git commit hash) that changes each build, causing all subsequent layers to be rebuilt.

generic

官方文档

https://docs.docker.com/engine/reference/builder/#arg

解决方案

  1. 将 ARG 声明放在所有稳定层之后(例如 apt-get install 之后),以便仅重建最终层,例如在 Dockerfile 末尾放置 'ARG GIT_COMMIT'。
  2. 在缓存依赖项之后使用单独的标签指令,如 'LABEL git.commit=$GIT_COMMIT',仅将 build-arg 用于元数据。

无效尝试

常见但无效的做法:

  1. 60% 失败

    Removing the --build-arg entirely loses the dynamic value needed for labeling or debugging.

  2. 90% 失败

    Adding the ARG after RUN commands in Dockerfile still invalidates cache for those layers.