DK构建镜像
从 Dockerfile 构建镜像,含平台指定、构建参数与免缓存
写好 Dockerfile 之后,用 docker build 把它变成可以运行、可以推送的镜像。构建过程的每一层都会被缓存,理解缓存命中规则能让构建从几分钟降到几秒——这也是这条命令最值得钻研的地方。
Docker 命令速查 / 镜像管理
docker build
-t app:1.0.0
-f ./Dockerfile
.
注意跨架构构建需要 buildx:docker buildx build --platform linux/amd64,linux/arm64 -t 名字 --push .;单机 build 出来的镜像不会自动推送。
参数说明
| 参数 | 占位符 | 默认值 | 说明 |
|---|---|---|---|
| 镜像名:标签 | {{tag}} | app:1.0.0 | — |
| 构建上下文 | {{context}} | . | 末尾的 . 不能省;上下文越大越慢,用 .dockerignore 排除 node_modules 等 |
| Dockerfile 路径 | {{dockerfile}} | -f ./Dockerfile | — |
| 目标平台 | {{platform}} | (空) | 示例:--platform linux/amd64 |
| 构建参数 | {{buildArgs}} | (空) | 示例:--build-arg NODE_ENV=production |
| 禁用构建缓存 | {{noCache}} | (空) | — |
| 其他参数 | {{extra}} | (空) | 示例:--rm --progress=plain |
构建镜像的关键要点
- 末尾的上下文路径不能省:命令最后那个 . 是把哪些文件发给 Docker 守护进程的「构建上下文」。写成 docker build -t app . 里的 . 指当前目录;漏掉会报「no context directory」。
- 上下文越大越慢:整个上下文目录会打包传给 daemon,node_modules、.git、日志都会拖慢构建。写一个 .dockerignore 排除它们,效果往往比改 Dockerfile 更明显。
- --build-arg 传的是构建期变量:只在 docker build 阶段有效,不会留进镜像运行时环境。需要运行时变量请用 docker run -e 或 ENV 指令。
- 跨 CPU 架构要用 buildx:普通 docker build 只能构建当前机器架构的镜像。要一次产出 amd64 + arm64 多架构镜像并推送,用 docker buildx build --platform linux/amd64,linux/arm64 -t 名字 --push .。
实战示例
基础构建并打标签
docker build -t myapp:1.0.0 .指定 Dockerfile、传构建参数、禁用缓存
docker build -f ./docker/Dockerfile.prod -t myapp:prod --build-arg NODE_ENV=production --no-cache .多架构构建并直接推送到仓库
docker buildx build --platform linux/amd64,linux/arm64 -t registry.example.com/myapp:1.0 --push .常见问题
为什么我改了代码,构建还是很快、像没生效?
Docker 按层缓存,COPY . . 这一层的内容变了才会让后续层失效。如果代码在 .dockerignore 里被排除了,或者你改的是未被 COPY 的文件,缓存就会一直命中。加 --no-cache 可强制全量重建验证。
-t 的标签有什么讲究?
格式是 名字:标签,不写标签默认是 latest。生产环境强烈建议用版本号或 Git 提交号做标签(如 myapp:1.2.3),latest 会随时间指向不同镜像,无法精确回滚。