user3842642
user3842642

Reputation: 49

Compile Java project with Docker

I am new to Docker. I have a problem with compiling the code with external library.

There is a lib folder (with the same level of "src" folder) that holding the library, such as abc.jar. I modified the Dockerfile as following. It compiled with no error but the project wasn't built with abc.jar.

# Compile our java files in this container
FROM openjdk:17-slim AS builder
COPY src /usr/src/project/src
COPY lib /usr/src/project/lib
COPY manifest.txt /usr/src/project/manifest.txt
WORKDIR /usr/src/project
RUN find . -name "*.java" | xargs javac -cp lib/abc.jar -d ./target
RUN jar cfm my_project.jar manifest.txt -C ./target/ .

# Copy the jar and test scenarios into our final image
FROM openjdk:17-slim
WORKDIR /usr/src/project
COPY --from=builder /usr/src/project/my_project.jar ./my_project.jar

manifest.txt has

Main-Class: Main
Class-Path: lib/abc.jar

Any help would be appreciated.

Thanks.

Upvotes: 1

Views: 3776

Answers (1)

Tasos P.
Tasos P.

Reputation: 4114

While you use the library for compiling your project, you don't include it in the final image. In multi-stage builds, each stage starts FROM a base image (openjdk:17-slim in this case) and unless you copy over the library, the final image will not include it.

This is how to do this:

# Copy the jar and test scenarios into our final image
FROM openjdk:17-slim
WORKDIR /usr/src/project
COPY --from=builder /usr/src/project/my_project.jar ./my_project.jar
COPY --from=builder /usr/src/project/lib/abc.jar ./lib/abc.jar
RUN java -jar my_project.jar

Upvotes: 2

Related Questions