'Is it possible to extract the Dockerfile from a docker container

I'm just starting out with Docker, and it would be very helpful to be able to see the Dockerfiles used to create existing docker images.

Even if the image was built by running commands manually, and then committing to a tag, it would be nice to be able to see how the image was made, both for learning purposes and for security.

Is there a way to extract a Dockerfile or list of commands used to build a given docker image?


Edit (November 2021): Since people are still upvoting this, I can say that based on the answers and comments, I settled on:

docker history --no-trunc --format '{{.CreatedBy}}' <image> | grep -v '#(nop)' | tac

It produces output that is easy to put in a Dockerfile. Example:

$ docker history --no-trunc --format '{{.CreatedBy}}' qemu | grep -v '#(nop)' | tac
ENV DEBIAN_FRONTEND=noninteractive
RUN /bin/sh -c apt-get update && apt-get -y upgrade # buildkit
RUN /bin/sh -c apt install -y qemu-system-arm gcc-arm-none-eabi build-essential cmake bison flex # buildkit
RUN /bin/sh -c useradd --create-home qemu # buildkit
WORKDIR /home/qemu
USER qemu
COPY baremetal-arm baremetal-arm # buildkit

But as I also wrote, I don't think there is a good way to extract the Dockerfile, so if you need it, and can't find the source code, maybe give the image a pass.



Solution 1:[1]

There is undocker available now. We can install it by using the pip command.

pip install git+https://github.com/larsks/undocker/ 

and use

docker save IMAGE_NAME | undocker -i -o OUTPUT_DIR

to extract the files from docker.

https://github.com/larsks/undocker/

Solution 2:[2]

There's a project dockerfile-from-image which could help you to do it directly.

It requires a single CLI command to recover the Dockerfile:

docker run -v /var/run/docker.sock:/var/run/docker.sock centurylink/dockerfile-from-image <IMAGE_TAG_OR_ID>

One has to have Docker already installed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rgov
Solution 2 Artem Oboturov