How To Copy A File From Host To Container Using Docker-py (docker Sdk)
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
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')
Solution 2:
Code snippet using memory BytesIO:
defcopy_to_container(container: 'Container', src: str, dst_dir: str):
""" src shall be an absolute path """
stream = io.BytesIO()
with tarfile.open(fileobj=stream, mode='w|') as tar, open(src, 'rb') as f:
info = tar.gettarinfo(fileobj=f)
info.name = os.path.basename(src)
tar.addfile(info, f)
container.put_archive(dst_dir, stream.getvalue())
Post a Comment for "How To Copy A File From Host To Container Using Docker-py (docker Sdk)"