python docker how to mount the directory from host to container

独自空忆成欢 提交于 2020-05-15 05:11:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!