简体   繁体   中英

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

I am using docker-py. I want to copy a file from docker container to host machine.

From docker-py documentation:

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

I could create container and start it but unable to get the file which gets copied from container to host. Can someone help me in pointing out if I am missing anything? I have /mydir/myshell.sh in my docker container which I tried copying to host.

>>> 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'>

It will be very helpful if someone can help me figuring out whether it is copying or not even copying the file.

copy is a deprecated method in docker and the preferred way is to use put_archive method. So basically we need to create an archive and then put it into the container. I know that's sounds weird, but that's what the API supports currently. If you, like me, think this can be improved, feel free to open an issue/feature request and I'll upvote it.

Here is a code snippet on how to copy a file to the container :

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生成的文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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