Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run different python scripts in parallel containers from same image

I am trying to do something very simple (I think), I want do build a docker image and launch two different scripts from the same image in parallel running containers.

Something as simple as

Container 1 -> print("Hello")

Container 2 -> print('World")

I did some research but some techniques seem a little over engineered and others do something like

CMD ["python", "script.py"] && ["python", "script2.py"]

which, isn't what I'm looking for.

I would love to see something like

$ docker ps
CONTAINER ID        IMAGE            CREATED          STATUS               NAMES
a7e789711e62        67759a80360c   12 hours ago     Up 2 minutes         MyContainer1
87ae9c5c3f84        67759a80360c   12 hours ago     Up About a minute    MyContainer2

But running two different scripts.

I'm still fairly new to all of this, so if this is a foolish question, I apologize in advance and thank you all for working with me.

like image 960
Chris Avatar asked Oct 27 '25 12:10

Chris


1 Answers

You can do this easily using Docker Compose. Here is a simple docker-compose.yml file just to show the idea:

version: '3'

services:
  app1:
    image: alpine
    command: >
      /bin/sh -c 'while true; do echo "pre-processing"; sleep 1; done'

  app2:
    image: alpine
    command: >
      /bin/sh -c 'while true; do echo "post-processing"; sleep 1; done'

As you see both services use the same image, alpine in this example, but differ in commands they run. Execute docker-compose up and see the output:

app1_1  | pre-processing
app2_1  | post-processing
app2_1  | post-processing
app2_1  | post-processing
app1_1  | pre-processing
app2_1  | post-processing
app1_1  | pre-processing
app2_1  | post-processing
...

In your case, you just change the image to your image, say myimage:v1, and change the service commands so that the first service definition will have command: python script1.py line and the second one command: python script2.py.

like image 113
constt Avatar answered Oct 30 '25 01:10

constt