Build gradle project inside a Docker

24,041

Solution 1

According to the Dockerfile for gradle:4.2.1-jdk8-alpine at , it has "gradle" as its default user. The files that you are copying from your app directory to docker image's app directory may not have right permissions for "gradle" user.

You should add three additional commands in your Dockerfile for setting the correct permissions:

FROM gradle:4.2.1-jdk8-alpine
WORKDIR /app
COPY --from=0 /app/myProject /app

USER root                # This changes default user to root
RUN chown -R gradle /app # This changes ownership of folder
USER gradle              # This changes the user back to the default user "gradle"

RUN ./gradlew build --stacktrace

Solution 2

Another option could be to use the ADD command instead of COPY and then use it's --chown option to change the owner of the file after copy. So the final Dockerfile would be even simpler.

FROM gradle:4.2.1-jdk8-alpine
WORKDIR /app
ADD --chown=gradle:gradle /app/myProject /app

RUN ./gradlew build --stacktrace
Share:
24,041
Sergii Bishyr
Author by

Sergii Bishyr

Software engineer and speaker. Always curious and driven to constantly develop and learn new things.

Updated on March 23, 2020

Comments

  • Sergii Bishyr
    Sergii Bishyr about 4 years

    I have a simple gradle project which I want to build inside the Docker container

    I have a multistage docker build. The first stage just clone the project from github. The second stage must build the project so I can run it in the final stage. But it fails on in

    FROM gradle:4.2.1-jdk8-alpine
    WORKDIR /app
    COPY --from=0 /app/myProject /app
    RUN ./gradlew build --stacktrace
    

    The command ./gradlew build --stacktrace cannot be executed and fails with the error:

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Could not update /app/.gradle/3.5-rc-2/file-changes/last-build.bin
    

    And the stacktrace:

    org.gradle.api.UncheckedIOException: Could not update /app/.gradle/3.5-rc-2/file-changes/last-build.bin
        at org.gradle.api.internal.changedetection.state.FileTimeStampInspector.updateOnFinishBuild(FileTimeStampInspector.java:72)
        at org.gradle.api.internal.changedetection.state.BuildScopeFileTimeStampInspector.stop(BuildScopeFileTimeStampInspector.java:38)
        at org.gradle.internal.concurrent.CompositeStoppable.stop(CompositeStoppable.java:98)
    .....
    Caused by: java.io.FileNotFoundException: /app/.gradle/3.5-rc-2/file-changes/last-build.bin (Permission denied)
        at java.io.FileOutputStream.open0(Native Method)
    ......
    

    Why the docker user doesn't have permission to create a file in the working directory and how to add these permissions? Simple RUN chmod 777 /app doesn't work and tells me: chmod: /app: Operation not permitted

  • Peter Dotchev
    Peter Dotchev over 4 years
    COPY also supports the --chown option, see docs.docker.com/engine/reference/builder/#copy