Home > other >  Run 2 Script at same time on Docker
Run 2 Script at same time on Docker

Time:07-19

I have a project and ı need to run 2 script when ı run mu Docker Image. Two of them this script has infinite loop. So none of them will stop.

I tried the use:

CMD ["python3", "main.py", "btcusdt"] 
CMD ["python3", "Flask_API/api_main.py"]

But ı discovered only last line of CDM is working.

Is there any way to do this ? Or should ı split my code and create 2 Docker Image ?

Thank you for time.

Here is my current not working Dockerfile:

FROM python:3.8

COPY requirements.txt requirements.txt


RUN pip install -r requirements.txt
COPY . .


CMD ["python3", "main.py", "btcusdt"]
CMD ["python3", "Flask_API/api_main.py"]

CodePudding user response:

There can be only one CMD instruction in the dockerfile if there is more than one, the last one will override the previous CMD instructions.

The better way I think is to create separate docker containers and talk to each other. here is a tutorial to do that : how to communicate between docker containers

But if you really need to run both scripts in a single container,

Here is the way

  • Create a bash script inside your project and include both bash commands in the script, here is an example.
#!/bin/bash

exec python3  main.py btcusdt &
exec python3 Flask_API/api_main.py

  • Add COPY instruction to Dockerfile to copy our bash script to the container and allow executable permission via RUN instruction.
COPY script.sh ./
RUN chmod a x script.sh
  • Now replace the previous two CMD instructions with one to execute our bash script.
CMD ["./script.sh"]

Here is the complete Dockerfile for you

FROM python:3.8

COPY requirements.txt requirements.txt


RUN pip install -r requirements.txt
COPY . .

RUN chmod a x script.sh

CMD ["./script.sh"]

  • Related