【问题标题】:Run Multiple Main Methods from the same Dockerfile从同一个 Dockerfile 运行多个主要方法
【发布时间】:2019-11-25 12:54:33
【问题描述】:

我有一个大型 Java 应用程序,在不同的类中有 5 个主要方法。我想将此应用程序作为 docker 容器运行。从DockerHub OpenJDK Image,我开始我的Dockerfile如下

FROM openjdk:latest
COPY . /usr/src/APP
WORKDIR /usr/src/APP`

我想添加行来运行主要方法。如果没有 Docker,我使用以下行运行应用程序

echo 'Starting App'
nohup $JAVA_HOME/bin/java .:./App.jar path.to.main.class1  >> 
/path/to/nohup/nohup.out 2>&1 &
nohup $JAVA_HOME/bin/java .:./App.jar path.to.main.class2  >> 
/path/to/nohup/nohup.out 2>&1 &
nohup $JAVA_HOME/bin/java .:./App.jar path.to.main.class3  >> 
/path/to/nohup/nohup.out 2>&1 &
nohup $JAVA_HOME/bin/java .:./App.jar path.to.main.class4  >> 
/path/to/nohup/nohup.out 2>&1 &
nohup $JAVA_HOME/bin/java .:./App.jar path.to.main.class5  >> 
/path/to/nohup/nohup.out 2>&1 &
echo 'App Started Successfully'`

是否可以在一个 docker 容器中运行上述场景?如果可能,Dockerfile中只能有一个ENTRYPOINTCMD指令怎么办?

【问题讨论】:

  • 全部加到一个.sh 并将这个.sh 添加到CMD
  • @LinPy 如果我在这种情况下使用 CMD 或 ENTRYPOINT 会有什么不同吗?
  • @RandaElBehery。有关 CMD 和 ENTRYPOINT 之间的差异,请参阅其他答案:stackoverflow.com/questions/21553353/…
  • Docker 文档解释了如何使用脚本或使用 supervisord:docs.docker.com/config/containers/multi-service_container。一般来说,我会使用supervisord 而不是脚本,因为它可以监视和重新启动死掉的服务。

标签: java docker dockerfile


【解决方案1】:

“如何从一个图像运行多个进程”的通常答案是运行多个容器。鉴于您展示的 Dockerfile,这相当简单:

# Build the image (once)
docker build -t myapp .

# Then run the five containers as background processes
docker run -d --name app1 java .:./App.jar path.to.main.class1
docker run -d --name app2 java .:./App.jar path.to.main.class2
docker run -d --name app3 java .:./App.jar path.to.main.class3
docker run -d --name app4 java .:./App.jar path.to.main.class4
docker run -d --name app5 java .:./App.jar path.to.main.class5

由于所有命令都非常相似,您可以编写一个脚本来运行它们

#!/bin/sh

# Use the first command-line argument as the main class
MAIN_CLASS="$1"
shift

# Can also set JAVA_OPTS, other environment variables, ...

# Run the application
exec java -jar App.jar "path.to.main.$MAIN_CLASS" "$@"

复制到图片中

COPY run_main.sh /usr/local/bin

然后当您启动容器时,只需运行该包装器

docker run -d --name app1 run_main.sh class1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2017-02-21
    • 2019-07-04
    • 2016-05-22
    • 2023-04-06
    • 2016-11-27
    • 1970-01-01
    相关资源
    最近更新 更多