How to copy a file from host to container using docker-py (docker SDK)

牧云@^-^@ 提交于 2020-01-23 06:42:25

问题


I know, there is possible way how to copy file bidirectionally between host and docker container using docker cp and also it is possible to obtain file from running container using docker-py. But I am not able to figure out how (or if it is even possible) copy file from host to running container using docker-py. Do you guys have any experiences with such kind of problem? Is it possible to do or I have to execute command using python os.system. I would like to avoid this solution.


回答1:


Something like this should work:

import os
import tarfile
import docker

client = docker.from_env()

def copy_to(src, dst):
    name, dst = dst.split(':')
    container = client.containers.get(name)

    os.chdir(os.path.dirname(src))
    srcname = os.path.basename(src)
    tar = tarfile.open(src + '.tar', mode='w')
    try:
        tar.add(srcname)
    finally:
        tar.close()

    data = open(src + '.tar', 'rb').read()
    container.put_archive(os.path.dirname(dst), data)

And then use it like:

copy_to('/local/foo.txt', 'my-container:/tmp/foo.txt')


来源:https://stackoverflow.com/questions/46390309/how-to-copy-a-file-from-host-to-container-using-docker-py-docker-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!