# 无法解决：无法解析密钥：密钥 'npm_token' 未找到

- **ID:** `docker/secret-not-found-in-build`
- **领域:** docker
- **类别:** build_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

Dockerfile 中通过 --mount=type=secret 引用的 BuildKit 密钥在构建命令中未提供，或者密钥 ID 不匹配。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Docker 24.0.6 | active | — | — |
| BuildKit 0.12.2 | active | — | — |
| Docker Compose v2.21.0 | active | — | — |
| Node.js 20.0.0 | active | — | — |

## 解决方案

1. ```
   在构建时传递密钥：'DOCKER_BUILDKIT=1 docker build --secret id=npm_token,src=./npm_token.txt -t myapp .'
   ```
2. ```
   使用 docker compose 并在 docker-compose.yml 中定义 secrets 部分：在 'secrets:' 下定义密钥，并在构建块中使用 'secrets: [npm_token]' 引用。
   ```
3. ```
   检查 Dockerfile 中的密钥 ID 是否完全匹配：确保 '--mount=type=secret,id=npm_token' 与构建命令中的 '--secret id=npm_token' 一致。
   ```

## 无效尝试

- **Setting the secret as an environment variable using ENV in Dockerfile** — Secrets are designed to avoid embedding in the image; ENV persists the value in layers. The error persists because the mount still expects a secret source. (85% 失败率)
- **Adding 'RUN --mount=type=secret,id=npm_token' without the --secret flag in the build command** — The mount declaration alone is insufficient; you must pass the secret from the host using '--secret id=npm_token,src=path' during build. (90% 失败率)
- **Creating a .env file and using docker compose build** — Compose does not automatically inject .env files as BuildKit secrets; they become build args, not secrets. The secret mount still fails. (70% 失败率)
