How to configure a standard path in a container created by Jib

2.2k Views Asked by At

I have a standard Sprinb Boot project.

And in the folder: src/main/resources/tmp/my_file.json, i have a json that I read in my Java code.


File file = new File("src/main/resources/tmp/my_file.json");

When running it locally it goes perfectly

With Jib I create a docker image:


<plugin>
                <groupId>com.google.cloud.tools</groupId>
                <artifactId>jib-maven-plugin</artifactId>
                <version>2.5.2</version>
                <configuration>
                    <from>
                        <image>adoptopenjdk:11-jre-hotspot</image>
                    </from>
                    <to>
                        <image>xxx/my_project:${version}</image>
                    </to>
                    <container>
                        <creationTime>USE_CURRENT_TIMESTAMP</creationTime>
                    </container>
                </configuration>
            </plugin>

When I run the container, it gives me an error that it cannot find the file:

java.io.FileNotFoundException: src/main/resources/tmp/my_file.json (No such file or directory)

The "src/main/resources" folder is the standard location for static resources.

Should I add any extra configuration to Jib to make the file available?

2

There are 2 best solutions below

0
On

You don't want your application to open a file based on the source project structure. At runtime (whether packaged as a JAR file or a container image), you won't have the src/ directory, and new File("src/...") will always fail. For example, even outside the Docker context, suppose you packaged your app as a runnable jar. Then running your app with java -jar <your-runnable.jar> will fail from the same error.

What Java folks usually do is to search files on a classpath, and this is pretty much the standard way to what you're trying to achieve. You can find many useful materials when you google "java get resources", but here are some references:


As of now, Jib 2.7.0 is the latest.

0
On

The problem is not with Jib but with your code.
Put "src/main/resources/" on the class path -- this is a standard way. And modify your code as below:

File file = new File("tmp/my_file.json");

When Jib creates an image, it copies all the resources from "src/main/resources/" to a directory ("/app/resources") on the image and puts that directory on the class path while launching your application.