python docker如何将目录从主机挂载到容器 [英] python docker how to mount the directory from host to container
问题描述
有人可以分享一些展示如何安装目录的py api示例吗? 我尝试过这种方法,但是看不到它的作用
can someone please share some examples of py apis showing how to mount the directories ? I tried like this but I dont see its working
dockerClient = docker.from_env()
dockerClient.containers.run('image', 'ls -ltr', volumes={os.getcwd(): {'bind': '/tmp/', 'mode': 'rw'}})
推荐答案
通过获取容器对象
根据以下内容更改代码:
By getting the container object
Change your code according to the following:
import os
import docker
client = docker.from_env()
container = client.containers.run('ubuntu:latest', 'ls -ltr /tmp', volumes={os.getcwd(): {'bind': '/tmp/', 'mode': 'rw'}}, detach=True)
print(container.logs())
# => b'total 4\n-rw-r--r-- 1 1000 1000 215 Feb 14 12:07 main.py\n'
在这里,容器对象是关键.要获取它,您必须将detach
参数传递为True
.
Here, the container object is the key. To get it, you have to pass detach
param as True
.
然后它可以打印出已执行命令的结果.
Then it can print out the result of the executed command(s).
获取输出的另一种方法是将stream
参数设置为True
,该参数返回日志生成器而不是字符串.如果detach为true,则将其忽略.
Another way to get the output is to set the stream
parameter to True
that returns a log generator instead of a string. Ignored if detach is true.
lines = client.containers.run('ubuntu:latest', 'ls -la /', volumes={os.getcwd(): {'bind': '/tmp/', 'mode': 'rw'}}, stream=True)
for line in lines:
print(line)
docker-py是docker引擎api的包装.因此,一切都在容器内执行,执行结果可通过REST获得.
docker-py is a wrapper around the docker engine api. Hence everything is executed inside the container and the result of the execution is available via REST.
如果要执行某些操作并即时获取其输出,可以使用subprocess
模块.
You can use subprocess
module if you want to execute something and get its output on the fly.
import subprocess
subprocess.run(["docker run ..."])
文档:
- docker-py:
client.containers.run(...)
- 引擎API:容器
- 子流程: subprocess.run
- docker-py:
client.containers.run(...)
- Engine API: containers
- Subprocess: subprocess.run
这篇关于python docker如何将目录从主机挂载到容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!