首页 > 解决方案 > 如何在 Dockerfile 中的 CMD 之后运行 python 脚本?

问题描述

我有一个为服务器公开 9000 端口的 docker 映像。服务器运行后,我需要执行依赖于服务器的 3 个 python 脚本,所以它们只能在 server.py 运行后执行,但是,在 CMD 命令之后,其他代码不会被执行并且仍然卡住。在同一个容器中运行 3 个脚本的可能建议是什么?

FROM python:3.7.3 as build

WORKDIR /app

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

COPY . . 

# CMD [ "python", "./server.py" ]   (The following 3 scripts depends on server.py for execution)

RUN python /app/script1.py
RUN python /app/script2.py
RUN python /app/script3.py

EXPOSE 9000

CMD [ "python", "./server.py" ]

标签: pythondockercmddocker-compose

解决方案


As written in the Dockerfile referece

There can only be one CMD instruction in a Dockerfile

The CMD instruction tells the container what its entry point is, and when running the container, that is what will be run.

If running python ./server.py is a blocking call (which I'm assuming it is, since it's called a server, and most likely responds to some kind of requests), then this won't be possible.

Instead, try restructuring your scripts so that they are run when the server is run, by doing everything you do in script1.py, script2.py, script3.py after the server has been started inside of server.py.

If instead this is about script1.py... sending requests to the server, I'd recommend not including those in the container. Instead, you can simply run those scripts, manually, from the terminal while the server container is running.


推荐阅读