Docker Container 上 Java Runtime Exec 的问题

问题描述

我正在尝试使用 GDAL 包(用于 ogr2ogr 命令)对 Java 应用程序进行 dockerize。

我的 Dockerfile 是:

FROM openjdk:10
ARG JAR_FILE=target/*.jar
copY ${JAR_FILE} app.jar

RUN apt-get update
RUN apt-get -y install python3-gdal
RUN apt-get -y install libgdal28
RUN apt-get -y install libgdal-perl-doc
RUN apt-get -y install libgdal-perl
RUN apt-get -y install libgdal-dev
RUN apt-get -y install gdal-data
RUN apt-get -y install gdal-bin

CMD ["java","-jar","/app.jar"]

在容器上运行的 Java 代码中有一个片段:

String command = "ogrinfo PG:\"host=host.docker.internal user=postgres dbname=test password=postgres\"";
Process process = Runtime.getRuntime().exec(command);

然后,输出为:

Unable to open datasource `PG:"host=host.docker.internal' with the following drivers.

但是,当我尝试直接从 bash 在容器上运行命令时,它成功了:

root@7b5fb10431cf:/# ogrinfo PG:"host=host.docker.internal user=postgres dbname=test password=postgres"
INFO: Open of `PG:host=host.docker.internal user=postgres dbname=test password=postgres'
      using driver `Postgresql' successful.

为什么会存在这样的差异?

解决方法

连接String的语法很重要PostgreSQL / PostGIS,可能问题出在Process实例Java Runtime.exec上。 PG 命令的运行方式必须与您直接在容器中运行的方式相同,这应该适合您:

String connection = "\"host=host.docker.internal user=postgres dbname=test password=postgres\"" ;
String[] commands = {"bash","ogrinfo","PG:"+connection};
Process process = Runtime.getRuntime().exec(commands);
,

基于@Hajed.Kh 的回答,我尝试了这个并且它有效:

    String[] commands = {
            "/bin/sh","-c",command
    };