Reputation: 181
I have a git repository as my build context for a docker image, and i want to execute gradle build and copy the jar file into the docker image and run it on entrypoint.
I know that we can copy the entire project into the image and run build and execute, however i want to run build first and copy only the jar executable into the image.
Is it possible to execute commands in the build context before copying the files?
Current way:
FROM azul/zulu-openjdk-alpine:8
COPY ./ .
RUN ./gradlew clean build
ENTRYPOINT ["/bin/sh","-c","java -jar oms-core-app-*-SNAPSHOT.jar"]
What i want:
FROM azul/zulu-openjdk-alpine:8
RUN ./gradlew clean build
COPY ./oms-core-app-*-SNAPSHOT.jar .
ENTRYPOINT ["/bin/sh","-c","java -jar oms-core-app-*-SNAPSHOT.jar"]
I cannot run the ./gradlew clean build before copying the project because the files don't exist in the image when running the command. But i want to run it in the source itself and then copy the jar.
Any help would be highly appreciated thank you.
Upvotes: 2
Views: 1295
Reputation: 158647
Conceptually this isn't that far off from what a multi-stage build does. Docker can't create files or run commands on the host, but you can build your application in an intermediate image and then copy the results out of that image.
# First stage: build the jar file.
FROM azul/zulu-openjdk-alpine:8 AS build
WORKDIR /app # avoid the root directory
COPY ./ . # same as "current way"
RUN ./gradlew clean build # same as "current way"
RUN mv oms-core-app-*-SNAPSHOT.jar oms-core-app.jar
# give the jar file a fixed name
# Second stage: actually run the jar file.
FROM azul/zulu-openjdk-alpine:8 # or some JRE-only image
WORKDIR /app
COPY --from=build /app/oms-core-app.jar .
CMD java -jar oms-core-app.jar
So the first stage runs the build from source; you don't need to run ./gradlew build
on the host system. The second stage starts over from just the plain Java installation, and COPY
only the jar file in. The second stage is what eventually runs, and if you docker push
the image it will not contain the source code.
Upvotes: 2