3.2 docker build 命令
使用 docker build 可以用 Dockerfile 创建一个 Docker 镜像。它会执行 Dockerfile 中的指令,创建可执行的容器镜像。
命令格式
docker build [选项] 本地路径、URL连接或标准输入(-)
命令别名:
docker image build,docker builder build。
命令说明:
-表示通过 标准输入STDIN给出 Dockerfile。
常用选项
选项
说明
-f <Dockerfile文件路径>指定Dockerfile 的路径(默认是
./Dockerfile)-t <镜像的名称[:标签]>设置新镜像的名称和标签(可以定义多个)
--build-arg设置创建时的变量(对应 Dockerfile 中的 ARG)。
--pull总是尝试拉取基础镜像的新版本
--no-cache创建时不使用缓存
-q安静模式,只输出镜像 ID
--rm创建成功后删除中间容器(默认 true)
--target创建多阶段镜像中的特定阶段
示例
我们使用 上节课编写的 Dockerfile 来创建名为 myubuntu_img 的镜像。
创建执行命令
docker build -t myubuntu_img -f Dockerfile .
- 新镜像的名称和标签为
myubuntu_img:latest - 使用的 Dockerfile 文件为
Dockerfile .是创建时使用本地的路径(当前路径)
执行过程如下:
weimingze@mzstudio:~$ sudo docker images;
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu 24.04 602eb6fb314b 2 months ago 78.1MB
weimingze@mzstudio:~$ sudo docker build -t myubuntu_img -f Dockerfile .
DEPRECATED: The legacy builder is deprecated and will be removed in a future release.
Install the buildx component to build images with BuildKit:
https://docs.docker.com/go/buildx/
... # 此处内容省略
Step 12/13 : VOLUME /root/mywebsite
---> Running in ad665e896f88
---> Removed intermediate container ad665e896f88
---> 761f35ffe848
Step 13/13 : CMD ["python3", "-m", "http.server", "--directory", "/root/mywebsite", "8000"]
---> Running in a57c2dec6218
---> Removed intermediate container a57c2dec6218
---> aadcd3546f14
Successfully built aadcd3546f14
Successfully tagged myubuntu_img:latest
weimingze@mzstudio:~$ sudo docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
myubuntu_img latest aadcd3546f14 26 seconds ago 168MB
ubuntu 24.04 602eb6fb314b 2 months ago 78.1MB
可见 myubuntu_img 创建成功。