Home > Software engineering >  Create File when my Spring boot is dockerized
Create File when my Spring boot is dockerized

Time:08-30

I'm running my Spring Boot application on docker and when I'm trying to create a new object I get this error (the object has an image where it saved in this path locally: application-fe/src/assets):

class path resource [application-fe/src/assets] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/usr/app/target/springbot

Does anyone know how to create a new file inside a docker container?

When running locally I was doing this:

String pathToSave = "application-fe/src/assets";
Resource resource = new ClassPathResource(pathToSave);
if (image != null) {
    File fileToSave = new File(resource.getFile()  "\\"  this.region(region, city)   ".png");

CodePudding user response:

Containers while useful for application isolation, are volatile in nature. Does the file you create require to be accessible or stored outside the container or when the container is not running ? In that case I would recommend you to add a path in your app.properties and mount that path to your server/laptop.

Use @Value annotations to map absolute path in spring boot and "-v" flag in docker run to map mount path. Also use mkdir to create the absolute path in your Dockerfile while building the image.

CodePudding user response:

The problem isn't that you're running inside a Docker container, the problem is that you are running your application from a .jar file.

You're getting the base path to write to using Resource resource = new ClassPathResource("application-fe/src/assets");.

If you compile the application to a set of .class files on the file system and run this, then the resource is located at an absolute path on the same file system as the .class files. It's likely that you could write to this local file system location.

When you package the compiled classes into a .jar file and run this, then the classpath containing the resource is inside the .jar file. You can't write to a location inside of a .jar file. This is what the does not reside in the file system: jar:file:/usr/app/target/springbot error message is trying to tell you.

If you really need to write to a file in the container, you should choose a file system path that is not on the classpath (that is, don't use ClassPathResource).

  • Related