[英]How to copy a file from host to container using docker-py (docker SDK)
[英]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'>
如果有人可以幫我弄清楚是復制還是不復制文件,將會非常有幫助。
copy
是put_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.