问题
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'}})
回答1:
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'
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).
By setting streams
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 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.
By using 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 ..."])
Doc:
- docker-py: client.containers.run(...)
- Engine API: containers
- Subprocess: subprocess.run
来源:https://stackoverflow.com/questions/54688176/python-docker-how-to-mount-the-directory-from-host-to-container