简体   繁体   中英

The problem with Java Runtime Exec on Docker Container

I am trying to dockerize a Java application with GDAL package (for ogr2ogr command).

My Dockerfile is:

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"]

In Java code running on container there is a snippet:

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

Then, output is:

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

But, when I tried to run command on the container directly from bash, it becomes successful:

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.

Why does such a difference exist?

The syntax of the connection String is important PostgreSQL / PostGIS , Probably the problem is in the Process instance Java Runtime.exec . the PG command must be run in the same way as you did directly in the container, this should works for you:

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

Based on @Hajed.Kh's answer, I tried this and it worked:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM