I'm facing an issue trying to run a simple java file that has a package name associated with it. My file is:
package com.example.springboot.folder.folder1;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
To compile the above I use javac HelloWorld.java
but to run it I need to go to the folder structure just before \com and run java com.example.springboot.folder.folder1.HelloWorld
which works fine.
I am now trying to build and run it using a dockerfile, my current docker file is as below :
FROM alpine
WORKDIR /root/testdir
COPY HelloWorld.java /root/testdir
RUN apk add openjdk8
ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk
ENV PATH $PATH:$JAVA_HOME/bin
RUN javac HelloWorld.java
CMD java -cp "java com.example.springboot.folder.folder1.HelloWorld"
It is placed at the same level as the HelloWorld.java program
When I try to build using docker build .
and run using docker run imageid
I get the below error:
Error: Could not find or load main class HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
Could anyone help out with where I might be going wrong?
CodePudding user response:
CMD java -cp "java com.example.springboot.folder.folder1.HelloWorld"
You can simply call this command : CMD java HelloWorld
, what will run your HelloWorld.class
file that you generate after your first command : RUN javac HelloWorld.java
.
But this not a good approach. You should provide to your Docker image a jar
file and then call this command : CMD ["java", "-jar", "/HelloWorld.jar"]
.
You will need to package your project and copy it in your docker image.
CodePudding user response:
You will need to preserve the package structure for this to work. Where you simply copy the java source code you'll need to copy the whole directory for this to work.
Here is what your Dockerfile should look like:
FROM alpine
WORKDIR /root/testdir
ADD com /root/testdir/com
RUN apk add openjdk8
ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk
ENV PATH $PATH:$JAVA_HOME/bin
RUN javac com/example/springboot/folder/folder1/HelloWorld.java
CMD ["java", "com.example.springboot.folder.folder1.HelloWorld"]
Of course, packaging is best done with a .jar, so doing what Harry Coder mentioned is probably your best bet.