使用 Docker exec 运行 Java 命令失败,并显示“没有此类文件或目录”

bar*_*azs 5 docker docker-java

我在 Scala 项目中使用Docker Java 客户端以编程方式创建映像并启动带有卷的容器,然后当这一切完成后,还会在附加卷之一中可用的 jar 文件中执行 Java 类。

  // Constructing the container and getting it's ID
  val containerID = dockerClient
    .createContainerCmd(imageID)
    .withName(s"${namePrefix}_${RandomStringUtils.randomAlphanumeric(12)}")
    .withTty(true)
    .withVolumes(volume)
    .withBinds(new Bind("/home/core/docker-dependencies", new Volume("/opt/dependencies")))
    .exec()
    .getId
  // Starting the container
  dockerClient
    .startContainerCmd(containerID)
    .exec()
Run Code Online (Sandbox Code Playgroud)

我试图运行的命令:

val command = s"""bash -c "java -cp /opt/dependencies/Platforms-assembly-0.2.4.jar com.org.test.platforms.common.Endpoint param1 param2}""""
Run Code Online (Sandbox Code Playgroud)

命令中引用的 jar 文件在创建容器时绑定的卷中可用。

我尝试运行不同版本的命令,例如简单的 Java 命令(不带bash -c),我还尝试了不同的位置,例如本地 PC 上的文件位置或运行 Docker 的计算机上的路径,遗憾的是结果相同。

  // Preparing the command for execution
  val executionID = dockerClient
    .execCreateCmd(containerID)
    .withCmd(command)
    .exec()
    .getId
  // Starting the execution
  dockerClient
    .execStartCmd(executionID)
    .withTty(true)
    .exec(new ExecStartResultCallback(System.out, System.err))
    .awaitCompletion()
Run Code Online (Sandbox Code Playgroud)

我收到的错误:

com.github.dockerjava.api.exception.NotFoundException: {"message":"rpc error: code = 2 desc = oci runtime error: exec failed: exec: \"bash -c \\\"java -cp /opt/dependencies/Platforms-assembly-0.2.4.jar  com.org.test.platforms.common.Endpoint param1 param2\\\"\": stat bash -c \"java -cp /opt/dependencies/Platforms-assembly-0.2.4.jar  com.org.test.platforms.common.Endpoint param1 param2\": no such file or directory"}
Run Code Online (Sandbox Code Playgroud)

如果我复制上述命令,附加到正在运行的容器并运行它,那么它会完美执行,这是我在这个问题上迷失的主要原因。据我了解,该卷应该在初始执行时可用,当我附加到容器时它当然可用。

Mur*_*nik 1

直接运行java会假设它在 中$PATH,这通常不是一个安全的假设。

更安全的方法是使用完全限定的路径,例如/usr/bin/java.