Skip to content

Instantly share code, notes, and snippets.

@prs-watch
Created August 11, 2019 11:38
Show Gist options
  • Select an option

  • Save prs-watch/7f4be986a8ff27e671f2b9cbeb6cb478 to your computer and use it in GitHub Desktop.

Select an option

Save prs-watch/7f4be986a8ff27e671f2b9cbeb6cb478 to your computer and use it in GitHub Desktop.
Script to generate Dockerfile from container.
#!/usr/bin/env python
# coding: utf-8
import docker
import jsondiff as jd
import re
import uuid
CLIENT = docker.from_env(timeout=600)
def gen_dockerfile(container_id):
contents = []
container = CLIENT.containers.get(container_id)
# FROM
contents.append("FROM {}".format(container.attrs.get("Config").get("Image")))
# RUN
contents.extend(get_run_command(container))
# write Dockerfile
with open("Dockerfile", "w", encoding="utf-8") as f:
f.write("\n".join(contents))
def get_run_command(container):
runs = []
# get diff of images' history
tmp_image_name = container.name + str(uuid.uuid4())
tmp_image = container.commit(tmp_image_name)
base_image = CLIENT.images.get(container.attrs.get("Config").get("Image"))
commands = sorted(
jd.diff(base_image.history(), tmp_image.history()).get(jd.insert), key=lambda x: x[1].get("Created")
)
for command in commands:
created_by = command[1].get("CreatedBy")
runs.append("RUN {}".format(created_by))
# delete tmp image
CLIENT.images.remove(tmp_image_name)
return runs
if __name__ == "__main__":
container_id = input(">> ")
gen_dockerfile(container_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment