简体   繁体   中英

python docker how to mount the directory from host to container

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'

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM