Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle dependency caching during docker multi stage build?

I have the following Dockerfile

FROM gradle:jdk13 AS appbuild
WORKDIR "/home/gradle/"
COPY --chown=gradle:gradle "./build.gradle" "/home/gradle/"
RUN gradle dependencies
COPY --chown=gradle:gradle "./src/" "/home/gradle/src/"
RUN gradle build --info

FROM openjdk:13
ENV LANG en_US.UTF-8
COPY --from=appbuild "/home/gradle/build/libs/frontend.jar" "/frontend.jar"
CMD ["java", "-jar", "-Dspring.profiles.active=default", "/frontend.jar"]

My aim is to prevent gradle from downloading the dependencies every time I build a docker image.

The command gradle dependencies downloads all the required java libraries in case they are missing.

Before the first gradle dependencies command I only copied the build.gradle in order to only download the dependencies and cache them.

When I run the gradle build command, why does it want to download all the files again? They are already present in one of the layers.

I have tried with RUN gradle clean build --info || return 0 instead of gradle dependencies, all the same.

like image 708
Gábor DANI Avatar asked Nov 23 '19 11:11

Gábor DANI


1 Answers

The GRADLE_USER_HOME environment variable isn't set by default. You'll need to explicitly set it, and then copy over the downloaded dependencies in the next stage.

FROM gradle:jdk13 AS cache
WORKDIR /app
ENV GRADLE_USER_HOME /cache
COPY build.gradle gradle.properties settings.gradle ./
RUN gradle --no-daemon build --stacktrace

FROM gradle:jdk13 AS builder
WORKDIR /app
COPY --from=cache /cache /home/gradle/.gradle
COPY src/ src/
RUN gradle --no-daemon build --stacktrace

FROM openjdk:jre-alpine
WORKDIR /app
RUN apk --no-cache add curl
COPY --from=builder /app/build/libs/frontend.jar /frontend.jar
ENV PORT 80
EXPOSE 80
HEALTHCHECK --timeout=5s --start-period=5s --retries=1 \
    CMD curl -f http://localhost:$PORT/health_check
CMD ["java", "-jar", "-Dspring.profiles.active=default", "/frontend.jar"]

Here's my original Dockerfile. I've modified it for yours, but haven't tested it, so you can refer to the original if you're in doubt.

like image 138
Neel Kamath Avatar answered Oct 09 '22 03:10

Neel Kamath