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

2 python python-2.7 docker dockerfile docker-compose

我正在使用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
Run Code Online (Sandbox Code Playgroud)

我可以创建容器并启动它但无法获取从容器复制到主机的文件.有人可以帮我指出我是否遗漏了什么?我在我的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'>
Run Code Online (Sandbox Code Playgroud)

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

Bor*_*sky 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
Run Code Online (Sandbox Code Playgroud)

  • 问题不是关于从容器复制吗? (3认同)

小智 1

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