dockerdockerpy

How can I "mount" a file into a directory in a docker container using docker-py?


I need to get a single file from my host machine into a per-existing directory in a docker container using docker-py. The directory shall not be overridden means mount is no option. Moving the directory to allow a shared volume between the host and the container is no option as well.


Solution

  • A single file on the host /tmp/hostfile.txt can be mounted into a container /tmp/containerfile.txt e.g. via pseudo code:

    import docker
    
    client = docker.from_env()
    stdout = client.containers.run(
        image='ubuntu',
        name='ubuntu',
        volumes={
            '/tmp/container.txt': {
                'bind': '/tmp/hostfile.txt',
                'mode': 'ro',
            }
        },
        network='host',
        command='ls /tmp',
    )
    

    (The string stdout contains the file.txt.)