docker build

根据 Dockerfile 构建镜像

语法

docker build [OPTIONS] PATH | URL | -

参数

参数说明示例级别
-t --tag 指定镜像名称和标签 docker build -t myapp:1.0 . 常用
-f --file 指定 Dockerfile 路径 docker build -f Dockerfile.prod . 常用
--no-cache 不使用缓存构建 docker build --no-cache -t myapp . 常用
--build-arg 设置构建时变量 docker build --build-arg VERSION=1.0 . 进阶
--target 多阶段构建指定目标阶段 docker build --target production . 进阶
--platform 指定目标平台 docker build --platform linux/amd64 . 进阶

示例

基本构建

docker build -t myapp:latest .
. 表示当前目录为构建上下文

使用指定 Dockerfile

docker build -f docker/Dockerfile.prod -t myapp:prod .
适合多环境不同 Dockerfile

多阶段构建指定阶段

docker build --target builder -t myapp:build .
只构建到 builder 阶段,用于调试

传入构建参数

docker build --build-arg NODE_VERSION=18 -t myapp .
Dockerfile 中用 ARG NODE_VERSION 接收

常见错误

failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory 当前目录没有 Dockerfile,用 -f 指定路径或切换到正确目录
COPY failed: file not found in build context COPY 的源文件不在构建上下文中,检查 .dockerignore 或文件路径
ERROR: failed to solve: process '/bin/sh -c xxx' did not complete successfully RUN 命令执行失败,检查命令是否正确、依赖是否安装

技巧

相关命令