Bash script to start Docker containers

10,823

To run many docker machines your script should be like this:

#!/bin/bash

for i in {1..10}
    do docker run —name docker-nginx$i -P -d nginx
    sleep 3
done

You should not use exec in this case as exec replaces the current process (your script) with the process resulting from executing its arguments (docker ...). This is why your script never gets past the first iteration.

Share:
10,823

Related videos on Youtube

Rui F Ribeiro
Author by

Rui F Ribeiro

Updated on September 18, 2022

Comments

  • Rui F Ribeiro
    Rui F Ribeiro over 1 year

    This script works:

    #!/bin/bash
    
    for i in {1..10}
        do echo “yes $i”
    done
    

    But when attempting to start several Docker containers it only starts the first container and exits:

    docker_run.sh

    #!/bin/bash
    
    for i in {1..10}
        do exec docker run —name docker-nginx$i -P -d nginx
        sleep 3
    done
    

    The sleep 3 was added to give it time. Not sure if it matters. Of course the script has to run with sudo permissions.

    • Atul Vekariya
      Atul Vekariya over 5 years
      Why do you use exec command? Try to do it running directly docker