错误:从引用 docker.io/library/python:3.11-slim 的缓存:缓存策略违规:层 2a3b4c5d6e7f 不被缓存策略 'cache-to: type=local' 允许
Error: cache from ref docker.io/library/python:3.11-slim: cache policy violation: layer 2a3b4c5d6e7f is not allowed by cache policy 'cache-to: type=local'
ID: policy/docker-layer-cache-policy-violation
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Docker 24.0.x | active | — | — | — |
| Docker 25.0.x | active | — | — | — |
| Docker 26.0.x | active | — | — | — |
根因分析
Docker BuildKit 的缓存策略配置(cache-to/cache-from)在指定的缓存导出类型和层的来源之间存在不匹配,通常发生在尝试将缓存从注册表镜像导出到本地目录时。
English
Docker BuildKit's cache policy configuration (cache-to/cache-from) has a mismatch between the specified cache export type and the layer's origin, often when trying to export cache from a registry image to a local directory.
官方文档
https://docs.docker.com/build/cache/解决方案
-
使用兼容的缓存导出类型。如果使用 'cache-to: type=local',确保缓存源也来自本地构建,而不是注册表镜像。或者,对于基于注册表的缓存,使用 'type=registry'。 示例: docker build --cache-from type=registry,ref=myregistry.com/myimage:cache \ --cache-to type=registry,ref=myregistry.com/myimage:cache,mode=max . -
通过仅使用 '--cache-from' 而不使用 '--cache-to' 来禁用缓存策略强制执行,或者为 cache-to 使用 'mode=min' 以仅导出最终层。 示例: docker build --cache-from type=local,src=path/to/cache \ --cache-to type=local,dest=path/to/cache,mode=min . -
在本地重建基础镜像并将其用作本地缓存源,以避免与注册表来源的层发生策略违规。 示例: # 本地构建基础镜像 docker build -t mybase:latest -f Dockerfile.base . # 将其用作缓存源 docker build --cache-from type=local,src=path/to/cache --cache-to type=local,dest=path/to/cache .
无效尝试
常见但无效的做法:
-
Clearing all Docker cache and rebuilding
40% 失败
Clearing all Docker cache and rebuilding from scratch loses all caching benefits and may not resolve the policy mismatch if the same configuration is used.
-
Changing the base image
65% 失败
Changing the base image to a different version might bypass the specific layer but the underlying policy issue remains for other layers.
-
Running docker system prune -a
75% 失败
Running 'docker system prune -a' removes all images and containers but does not fix the cache policy configuration in the Dockerfile or build command.