【问题标题】:How to run two processes with dockerfile?如何使用 dockerfile 运行两个进程?
【发布时间】:2022-12-05 00:19:41
【问题描述】:

我需要运行 uvicorn 服务器进程和我的 python 脚本(这是另一个进程)。 由于 uvicorn 启动了一个不会结束的进程,因此第二个命令将不会启动。所以我问你是否知道一些解决方法来解决这个问题。

我试图执行此命令:

CMD cd Manager ; uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 && python ManagerBot.py

还有这个:

CMD cd Manager ; uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 ; python ManagerBot.py

但是脚本没有启动(只有 uvicorn 服务器启动) 我提醒您,脚本是另一个不会结束的过程,因此“反之亦然”将不起作用。

【问题讨论】:

  • 编写一个在容器启动时调用的入口点脚本,PID 为 1,然后使用您的入口点脚本在后台启动其他进程

标签: python docker server dockerfile command


【解决方案1】:

要在 Docker 容器中运行多个进程,您可以在 Dockerfile 中使用 ENTRYPOINT 或 CMD 指令。要在后台运行多个进程,可以使用 & 运算符在后台运行每个命令。例如:

ENTRYPOINT uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 & python ManagerBot.py

或者,您可以创建一个运行这两个命令的 shell 脚本,然后使用 ENTRYPOINT 或 CMD 指令运行该 shell 脚本。这使您可以轻松管理流程并确保在容器启动时运行这两个命令。例如:

#!/bin/sh

# Start the uvicorn server
uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 &

# Start the python script
python ManagerBot.py

然后,在您的 Dockerfile 中,您可以使用 ENTRYPOINT 或 CMD 指令来运行 shell 脚本:

ENTRYPOINT ["/path/to/script.sh"]

或者:

CMD ["/path/to/script.sh"]

这些方法中的任何一种都应该允许您在单个 Docker 容器中运行多个进程。

【讨论】:

    【解决方案2】:

    创建一个包装器脚本,例如run.sh:

    #!/bin/bash
    
    # Start the first process
    uvicorn ManagerBot:app --host 0.0.0.0 --port 8000 &
      
    # Start the second process
    python ManagerBot.py &
      
    # Wait for any process to exit
    wait -n
      
    # Exit with status of process that exited first
    exit $?
    

    然后,在 Dockerfile 中:

    ... 
    COPY run.sh /run.sh
    RUN chmod +x /run.sh
    ENTRYPOINT ["/run.sh"]
    

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多