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

前端 未结 1 377
遥遥无期
遥遥无期 2021-02-08 08:38

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

1条回答
  •  隐瞒了意图╮
    2021-02-08 08:48

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

    0 讨论(0)
提交回复
热议问题