如何从Docker image中逆向生成Dockerfile
在使用Docker
时,我们可能会遇到这样一种情况:已经创建了一个镜像,但当我们想要提取或修改相应的Dockerfile
时,却找不到它。这时,我们不想重新编写Dockerfile
,而希望从已有的镜像中恢复它。
Dockerfile
FROM alpine:latest
WORKDIR /app
COPY hello.txt .
CMD ["sh", "-c", "cat hello.txt && tail -f /dev/null"]
构建镜像
root@linux:/data/service/test-image# sudo docker build -t test-image .
[sudo] ghost 的密码:
[+] Building 0.1s (8/8) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 141B 0.0s
=> [internal] load metadata for docker.io/library/alpine:latest 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [1/3] FROM docker.io/library/alpine:latest 0.0s
=> [internal] load build context 0.0s
=> => transferring context: 49B 0.0s
=> [2/3] WORKDIR /app 0.0s
=> [3/3] COPY hello.txt . 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:f3556af232a391ed7e8a0adaec3bcc3eb4195e5a69e12d9994ba10d14f1a 0.0s
=> => naming to docker.io/library/test-image 0.0s
运行镜像
root@linux:/data/service/test-image# sudo docker run -d test-image
80c9aa7ef7732a5155df419273704b72b576651855df8d49388c30c4853962dc
root@linux:/data/service/test-image# sudo docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
80c9aa7ef773 test-image "sh -c 'cat hello.tx…" 10 seconds ago Up 9 seconds crazy_yalow
root@linux:/data/service/test-image# sudo docker logs 80c9aa7ef773
hello alpine
逆向dockerfile
docker history
我们可以docker
自己带的命令docker history
来通过查看分层的方式尝试确定更改过的地方。
命令格式
docker history --format {{.CreatedBy}} --no-trunc=true 镜像 |sed "s?/bin/sh\ -c\ \#(nop)\ ??g"|sed "s?/bin/sh\ -c?RUN?g" | tac
Example
root@linux:/data/service/test-image# sudo docker history --format {{.CreatedBy}} --no-trunc=true test-image |sed "s?/bin/sh\ -c\ \#(nop)\ ??g"|sed "s?/bin/sh\ -c?RUN?g" | tac ADD file:5758b97d8301c84a204a6e516241275d785a7cade40b2fb99f01fe122482e283 in / CMD ["/bin/sh"] WORKDIR /app COPY hello.txt . # buildkit CMD ["sh" "-c" "cat hello.txt && tail -f /dev/null"]
image2df
安装
image2df
工具root@linux:/data/service/test-image# echo "alias image2df='sudo docker run --rm --privileged -v /var/run/docker.sock:/var/run/docker.sock cucker/image2df'" >> ~/.bashrc root@linux:/data/service/test-image# . ~/.bashrc
逆向`dockerfile
root@linux:/data/service/test-image# image2df test-image # ========== Dockerfile ========== FROM test-image:latest ADD alpine-minirootfs-3.21.3-x86_64.tar.gz / # buildkit CMD ["/bin/sh"] WORKDIR /app COPY hello.txt . # buildkit CMD ["sh", "-c", "cat hello.txt && tail -f /dev/null"]