Search code examples
bashdockerdocker-run

Mounting multiple volumes present in Json file as List


I would like to mount the multiple volumes of folders in the docker run command. But it is getting failed while creating the container using script. The volumes folder names are fetched from the json file.

When i tried separately as

docker run -it -v /home/sample_1: /test1  -v  /home/sample_2: /test2 ubuntu /bin/bash

Then it is working fine.

But i would like to bind the multiple volumes as represented below.

sample.json File

{
        "volume_mount": ["/home/sample_1:/test1", "/home/sample_2:/test2"],
        "name": "deva"
}

docker_script.sh

#!/bin/bash
volume_mount=$(jq -r '."volume_mount"//empty' sample.json )
echo $volume_mount
docker run -it ${volume_mount:+--volume ${volume_mount}} ubuntu /bin/bash

Expected

Container should create and mount two volumes /test1 and /test2 data in the container.

Error


./docker_sample.sh 
++ jq -r '."volume_mount"//empty' sample.json 
+ volume_mount='[ "/home/sample_1:/test1", "/home/sample_2:/test2" ]' 
+ echo '[' '"/home/sample_1:/test1",' '"/home/sample_2:/test2"' ']' [ "/home/sample_1:/test1", "/home/sample_2:/test2" ] 
+ docker run -it --volume '[' '"/home/sample_1:/test1",' '"/home/sample_2:/test2"' ']' ubuntu /bin/bash 
docker: invalid reference format

Solution

  • Your docker command in docker_script.sh equals to next:

    docker run -it --volume [ "/home/sample_1:/test1", "/home/sample_2:/test2" ] ubuntu /bin/bash
    

    Why do you think this syntax work? You should let it look like the command you used at first: -v xxx:xxx -v xx:xx, something like follows:

    docker_script.sh:

    #!/bin/bash
    volume_mount=$(jq -r .volume_mount[] sample.json)
    volume_string=""
    for per_volume_mount in $volume_mount
    do
        volume_string="$volume_string -v $per_volume_mount"
    done
    docker run -it $volume_string ubuntu /bin/bash