# 错误：从引用 docker.io/library/python:3.11-slim 的缓存：缓存策略违规：层 2a3b4c5d6e7f 不被缓存策略 'cache-to: type=local' 允许

- **ID:** `policy/docker-layer-cache-policy-violation`
- **领域:** policy
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 78%

## 根因

Docker BuildKit 的缓存策略配置（cache-to/cache-from）在指定的缓存导出类型和层的来源之间存在不匹配，通常发生在尝试将缓存从注册表镜像导出到本地目录时。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Docker 24.0.x | active | — | — |
| Docker 25.0.x | active | — | — |
| Docker 26.0.x | active | — | — |

## 解决方案

1. ```
   使用兼容的缓存导出类型。如果使用 '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 .
   ```
2. ```
   通过仅使用 '--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 .
   ```
3. ```
   在本地重建基础镜像并将其用作本地缓存源，以避免与注册表来源的层发生策略违规。
示例：
  # 本地构建基础镜像
  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** — 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. (40% 失败率)
- **Changing the base image** — Changing the base image to a different version might bypass the specific layer but the underlying policy issue remains for other layers. (65% 失败率)
- **Running docker system prune -a** — Running 'docker system prune -a' removes all images and containers but does not fix the cache policy configuration in the Dockerfile or build command. (75% 失败率)
