每当 docker 从 Dockerfile 成功执行 RUN 命令时,a new layer in the image filesystem 就会被提交。您可以方便地使用这些图层 ID 作为图像来启动新容器。
获取以下 Dockerfile:
FROM busybox
RUN echo 'foo' > /tmp/foo.txt
RUN echo 'bar' >> /tmp/foo.txt
并构建它:
$ docker build -t so-26220957 .
Sending build context to Docker daemon 47.62 kB
Step 1/3 : FROM busybox
---> 00f017a8c2a6
Step 2/3 : RUN echo 'foo' > /tmp/foo.txt
---> Running in 4dbd01ebf27f
---> 044e1532c690
Removing intermediate container 4dbd01ebf27f
Step 3/3 : RUN echo 'bar' >> /tmp/foo.txt
---> Running in 74d81cb9d2b1
---> 5bd8172529c1
Removing intermediate container 74d81cb9d2b1
Successfully built 5bd8172529c1
您现在可以从00f017a8c2a6、044e1532c690 和5bd8172529c1 启动一个新容器:
$ docker run --rm 00f017a8c2a6 cat /tmp/foo.txt
cat: /tmp/foo.txt: No such file or directory
$ docker run --rm 044e1532c690 cat /tmp/foo.txt
foo
$ docker run --rm 5bd8172529c1 cat /tmp/foo.txt
foo
bar
当然,您可能想启动一个 shell 来探索文件系统并尝试命令:
$ docker run --rm -it 044e1532c690 sh
/ # ls -l /tmp
total 4
-rw-r--r-- 1 root root 4 Mar 9 19:09 foo.txt
/ # cat /tmp/foo.txt
foo
当 Dockerfile 命令中的一个失败时,您需要做的是查找 上一层的 id 并在根据该 id 创建的容器中运行 shell:
docker run --rm -it <id_last_working_layer> bash -il
在容器中一次:
- 尝试失败的命令,然后重现问题
- 然后修复命令并测试它
- 最后使用固定命令更新您的 Dockerfile
如果您确实需要在实际失败的层中进行试验,而不是从最后一个工作层开始,请参阅Drew's answer。