javadocker

Docker run fails with NoClassDefFoundError - even though dependant jar is in classpath


I am a docker newbie. I am trying to run a java class in the container. My main class is depending on a local jar. Am able to add the jar to the docker image and able set the jar in the classpath.

But still, when run the container it fails with "Exception in thread "main" java.lang.NoClassDefFoundError"

My Dockerfile

FROM java:8

WORKDIR /

ADD Test.jar Test.jar

ADD Dependant.jar Dependant.jar

RUN mkdir /usr/myjars

COPY /Dependant.jar /usr/myjars/Dependant.jar

ENV CLASSPATH .:/usr/myjars/Dependant.jar

RUN export CLASSPATH=.:/usr/myjars/Dependant.jar

CMD ["java",  "-jar", "Test.jar"]

Please help me to identify issue


Solution

  • Normally when we try to run a java class from a JAR file, JVM won't consider the environment CLASSPATH. Instead it will look class path defnition of manifest file in the jar.

    Refer : https://docs.oracle.com/javase/tutorial/deployment/jar/downman.html

    Considering the case, I have corrected the creation of my CheckSum.jar/Dependant.jar with following manifest.

    MANIFEST.MF

    Manifest-Version: 1.0
    Class-Path: . /usr/myjars/PaytmChecksum.jar
    Main-Class: TestChecksumGeneration
    

    following is my corrected Docker file.

    Dockerfile

    FROM java:8
    
    COPY CheckSum.jar /
    
    ENV JARDIR=/usr/myjars
    
    RUN mkdir -p ${JARDIR}
    
    COPY PaytmChecksum.jar ${JARDIR}
    
    ENTRYPOINT java -jar /CheckSum.jar
    

    Note : I have not provided any CLASSPATH to my docker container.