Docker Community Forums

Share and learn in the Docker community.

Official Python Image: How to execute multiple scripts at once?


I use the python image to run multiple python 2 scripts every few minutes. But this way I have to start a container multiple times. Is there a best practice to avoid this?

docker run -it --rm --name my-running-script -v “$PWD”:/usr/src/myapp -w /usr/src/myapp python:3 python writeweather “Hannover,de”
docker run -it --rm --name my-running-script -v “$PWD”:/usr/src/myapp -w /usr/src/myapp python:3 python writetwitter “MarcTV”
docker run -it --rm --name my-running-script -v “$PWD”:/usr/src/myapp -w /usr/src/myapp python:3 python writeyoutube

Thanks for your help!

My approach would be to define the entrypoint/cmd fields in the image in a way to have the container running in the background. For example:

docker run -it -d --rm --name my-running-script -v “$PWD”:/usr/src/myapp -w /usr/src/myapp python:3 /in/bash

Notice the “detached” flag -d above. Your container will be running in the background as you can see by inspecting via docker ps. This trick is possible for this image but in other cases, it depends on the image you use. More specifically, it depends on the entrypoint and also if it has bash installed in the image. (This is a side note and adding for clarification, FYI) Then you could execute the commands on the container directly using exec:

docker exec my-running script {cmd}

where {cmd} would be:

  • python writeweather “Hanwriteyoutubenover,de”
  • python writetwitter “MarcTV”
  • python

I notice you are running your container in interactive mode. Another possible approach would be accessing the container by creating a bash session and then executing the commands within the container via the interactive session. It would be something like this:

docker run -it --rm --name my-running-script -v “$PWD”:/usr/src/myapp -w /usr/src/myapp python:3 /bin/bash

At this point you are in a session inside the container and you could execute your commands one after the other:

 python writeweather “Hanwriteyoutubenover,de”
 python writetwitter “MarcTV”

You exit the container with ‘exit’ which will stop the container and it is removed immediately as you have the --rm flag in the command.