如何使用docker-py中的副本将文件从容器复制到主机

时间:2016-10-12 22:33:13

标签: python python-2.7 docker docker-compose dockerfile

我正在使用docker-py。我想将文件从docker容器复制到主机。

来自docker-py文档:

copy

Identical to the docker cp command. Get files/folders from the container.

Params:

    container (str): The container to copy from
    resource (str): The path within the container

Returns (str): The contents of the file as a string

我可以创建容器并启动它但无法获取从容器复制到主机的文件。有人可以帮我指出我是否遗漏了什么?我在我的docker容器中有/mydir/myshell.sh,我尝试复制到主机。

>>> a = c.copy(container="7eb334c512c57d37e38161ab7aad014ebaf6a622e4b8c868d7a666e1d855d217", resource="/mydir/myshell.sh") >>> a
<requests.packages.urllib3.response.HTTPResponse object at 0x7f2f2aa57050>
>>> type(a)
<class 'requests.packages.urllib3.response.HTTPResponse'>

如果有人可以帮我弄清楚是否复制文件,将会非常有帮助。

2 个答案:

答案 0 :(得分:7)

copy是docker中不推荐使用的方法,首选方法是使用put_archive方法。所以基本上我们需要创建一个存档然后将它放入容器中。我知道这听起来很奇怪,但这是API目前支持的内容。如果您和我一样认为可以改进,请随时打开问题/功能请求,然后我就会对其进行投票。

以下是有关如何将文件复制到容器的代码段:

def copy_to_container(container_id, artifact_file):
    with create_archive(artifact_file) as archive:
        cli.put_archive(container=container_id, path='/tmp', data=archive)

def create_archive(artifact_file):
    pw_tarstream = BytesIO()
    pw_tar = tarfile.TarFile(fileobj=pw_tarstream, mode='w')
    file_data = open(artifact_file, 'r').read()
    tarinfo = tarfile.TarInfo(name=artifact_file)
    tarinfo.size = len(file_data)
    tarinfo.mtime = time.time()
    # tarinfo.mode = 0600
    pw_tar.addfile(tarinfo, BytesIO(file_data))
    pw_tar.close()
    pw_tarstream.seek(0)
    return pw_tarstream

答案 1 :(得分:3)

在我的python脚本中,我添加了一个使用docker run -it -v artifacts:/artifacts target-build运行docker的调用,这样我就可以在artifacts文件夹中运行docker生成的文件。