Search code examples
dockerspring-bootdockerfile

File Upload by docker container


I have a spring boot app. Docker container has no permission to create a file.

docker file:

FROM openjdk:8-jdk-alpine

VOLUME /tmp

ADD /build/libs/file-upload-service-2.0.0.jar app.jar

ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

Image Build Command:

docker build -t file-upload-service .

Image Run Command:

docker run -d --name file-upload-service -p 9104:9104 file-upload-service:latest

Folder Permissions:

sudo chown -R  root:docker  /home/storage/

sudo chmod -R 777 /home/storage/

When running with java -jar then the application can create the file.


Solution

  • Problem

    You're expecting your code inside the docker container to locate a file in your host's filesystem. A docker container is a fully contained(as the name suggests) runtime environment with its private filesystem, network, etc. You can not directly access the host's filesystem from your docker container unless you have some requisite configurations (mounting) in your docker run .. command or the compose file.

    Solution

    You'll have to mount the volume /home/storage inside the docker container to read/write from/to that location from within the container. To do so, after changing the filesystem permissions in your host (which you have already), use the following run command to start the container:

    docker run -d --name file-upload-service -v /home/storage:/home/storage -p 9104:9104 file-upload-service:latest
    

    The -v flag in the above command tells docker to mount the /home/storage directory of the host machine (the left side of :) to the /home/storage directory of the container (the right side of :). You can change these directories according to your use case.