(七)dockerfile调试
(1)dockerfile调试过程
-
从 base 镜像运行一个容器。
-
执行一条指令,对容器做修改。
-
执行类似 docker commit 的操作,生成一个新的镜像层。
-
Docker 再基于刚刚提交的镜像运行一个新容器。
-
重复 2-4 步,直到 Dockerfile 中的所有指令执行完毕。
从这个过程可以看出,如果 Dockerfile 由于某种原因执行到某个指令失败了,我们也将能够得到前一个指令成功执行构建出的镜像,这对调试 Dockerfile 非常有帮助。我们可以运行最新的这个镜像定位指令失败的原因。
例如:Dockerfile 内容如下
root@cuiyongchao:/dockerfile# cat Dockerfile
FROM busybox
RUN touch tmpfile
RUN /bin/bash -c echo "zhangsan is lisi"
COPY testfile /
执行docker built:
root@cuiyongchao:/dockerfile# docker build -t iamge-debug .
Sending build context to Docker daemon 3.072kB
Step 1/4 : FROM busybox
latest: Pulling from library/busybox
9758c28807f2: Pull complete
Digest: sha256:a9286defaba7b3a519d585ba0e37d0b2cbee74ebfe590960b0b1d6a5e97d1e1d
Status: Downloaded newer image for busybox:latest
---> f0b02e9d092d
Step 2/4 : RUN touch tmpfile
---> Running in 6ec24996c8fa
Removing intermediate container 6ec24996c8fa
---> c7bef448b12f
Step 3/4 : RUN /bin/bash -c echo "zhangsan is lisi"
---> Running in 8e8f2f1fff93
/bin/sh: /bin/bash: not found
The command '/bin/sh -c /bin/bash -c echo "zhangsan is lisi"' returned a non-zero code: 127
root@cuiyongchao:/dockerfile#
Dockerfile 在执行第三步 RUN 指令时失败。我们可以利用第二步创建的镜像 c7bef448b12f 进行调试,方式是通过 docker run -it
启动镜像的一个容器。
root@cuiyongchao:/dockerfile# docker run -it c7bef448b12f
/ # /bin/bash
sh: /bin/bash: not found
/ #
手工执行 RUN 指令定位失败的原因是 busybox 镜像中没有 bash。虽然这是个极其简单的例子,但它很好地展示了调试 Dockerfile 的方法。