Skip to content
Advertisement

How to pass volume to docker container?

I am running the below docker command :

docker run -d -v /Users/gowthamkrishnaaddluri/Documents/dfki_sse/demo:/quantum-demo/ -it demo python3 /quantum-demo/circuit.py --res './'

I am trying to run the above command in python and I have the code as follows:

container = client.create_container( image='demo', stdin_open=True, tty=False, command="python3 /quantum-demo/circuit.py --res='./'", volumes=['/Users/gowthamkrishnaaddluri/Documents/dfki_sse/demo', '/quantum-demo/'], detach=True, ) client.start(container=container.get('Id'))

I am not able to see the files which get generated when the python file(circuit.py) is run. The files get generated when I just run the docker command , when I use the container api the file is not seen in the directory. Am I doing something wrong on using the volumes in the client create container? Thanks!

How can I rectify the above problem so that I can map the volume properly? Or please let me know how can I use docker volumes so that the file generated in the docker folder can be copied to the local directory( such as saved neural network model after training)

Thanks!

Advertisement

Answer

Hi 👋🏻 Hope you are doing well!

So instead of the list, you should use dict and also you should use another method. An example is below:

import docker

client = docker.from_env()
client.containers.run(
    image="python",
    auto_remove=True,
    detach=True,
    tty=False,
    stdin_open=True,
    volumes={
        # path on your machine/host
        "/Users/volodymyr/Development/sandbox/stackoverflow/file.py": {
            "bind": "/mnt/file.py",  # path inside the container
            "mode": "rw",
        }
    },
    command=["python", "/mnt/file.py", "-w", "world!"],
)
# file.py
import argparse


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-w", "--word")
    args = parser.parse_args()

    print(f"Hello {args.word!s}.")

I tested this code on my machine and it works. (docker sdk version is 6.0.1)

Docs: https://docker-py.readthedocs.io/en/stable/containers.html

Advertisement