2

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.

5
  • What do you mean by "wasn't built with the abc.jar"? Commented Apr 13, 2021 at 16:58
  • I got ClassNotFound exception when I run the program when calling the class in abc.jar. Also, I use "jar -tf my_project.jar" to view the project structure, I don't see the lib/abc.jar within my project. Commented Apr 13, 2021 at 17:13
  • That isn't how Java works unless you explicitly create a fat jar (e.g., via Maven/Gradle). Commented Apr 13, 2021 at 17:55
  • You should copy abc.jar to target image and add it to classpath when running your jar. Commented Apr 13, 2021 at 18:57
  • Hi Sokolov, thanks for helping. Could you please elaborate more on how to do that? Commented Apr 14, 2021 at 18:51

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Appreciate for your help Tasos.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.