The problem with Java Runtime Exec on Docker Container

927 views Asked by At

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?

2

There are 2 answers

1
Hajed.Kh On

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);
0
Oğuzcan Budumlu On

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

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