繁体   English   中英

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

[英]How to copy a file from container to host using copy in docker-py

我正在使用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'>

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

copyput_archive不推荐使用的方法,首选方法是使用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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM