skip to Main Content

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");

2

Answers


  1. 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.

    Add below to your Dockerfile:

    RUN mkdir -p /appl/pictures/ ==> This maybe where you can store your image file from application

    In docker run/compose command you can add -v flag as:

    docker run .... -v <absolute server path>:<image file path inside container> ...
    

    eg:

    docker run .... -v /appl/pictures/:/appl/pictures/ ...
    

    So now all images that you create inside container will be mounted into server /appl/pictures/ and will be persistent even if container is destroyed or stopped.

    Login or Signup to reply.
  2. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search