dockerfile编写的过程中,不可避免会遇到运行构建新镜像错误的问题,那么我们应该怎样调试dockerfile呢。其实,当我们遇到某个指令失败时,我们也能够得到前一个指令构建的镜像。因此,我们可以进入到前一个临时镜像,调试下一个指令。
在/root/debug-dockerfile目录下创建一个Dockerfile构建一个包含有错误命令的新镜像
root@localhost debug-dockerfile]# pwd
/root/debug-dockerfile
Dockerfile
FROM centos:7.4.1708
RUN touch tmpfile
RUN cp tmpfile tmpdir/
很明显,该dockerfile的第三个命令是会运行失败的,因为当前目录没有tmpdir目录。
运行Dockerfile后,报错信息如下,在step3,即 RUN cp tmpfile tmpdir/ 时出现了错误。
[root@localhost debug-dockerfile]# docker build -t debug-dockerfile .
Sending build context to Docker daemon 2.56kB
Step 1/3 : FROM centos:7.4.1708
---> 295a0b2bd8ea
Step 2/3 : RUN touch tmpfile
---> Running in 7530981ccd45
Removing intermediate container 7530981ccd45
---> 8408a48380c2
Step 3/3 : RUN cp tmpfile tmpdir/
---> Running in a50d0a45ce94
cp: cannot create regular file 'tmpdir/': Not a directory
The command '/bin/sh -c cp tmpfile tmpdir/' returned a non-zero code: 1
这时,我们可以进入到前面一个指令中获取到的临时镜像8408a48380c2,调试下一个指令。
[root@localhost debug-dockerfile]# docker run -it 8408a48380c2
通过ll命令,我们可以看到上一个命令创建的文件tmpfile