Running docker from bash script

2.7k Views Asked by At

I am using a tool (gatk) distributed as a docker image and try to use its commands in a shell script. I run the docker in detached mode.

sudo docker run --name my_container -d -v ~/test:/gatk/data -it broadinstitute/gatk:4.1.9.0

Then I run the commands from shell script

#!/bin/bash
docker exec my_container gatk command1
wait
docker exec my_container gatk command2

command2 needs input from command1 so I use wait, but still command2 is executed before command 1 is finished. I also tried

#!/bin/bash
docker exec my_container gatk command1
docker wait my_container
docker exec my_container gatk command2

but then the script does not continue running after command1 is completed.

2

There are 2 best solutions below

0
On

You can run both commands in a single shot:

docker run image /bin/bash -c "gatk command1 && gatk command2"
0
On

I managed to solve it. The problem was is that when I ran docker exec I did not define it to receive input from the shell. Adding -i flag to docker exec solved the problem. Here is the full solution.

I start docker in detached mode

sudo docker run --name my_container -d -v ~/test:/gatk/data -it broadinstitute/gatk:4.1.9.0

Now I can close the terminal, the docker container is up and running and I can use it in a new terminal. I generate a bash script called myscript.sh with the following code.

#!/bin/bash
docker exec -i my_container gatk command1
wait
docker exec -i my_container gatk command2

I run the script, disown it and close the terminal.

./myscript.sh&disown;exit