4

I realize that this question may already have been asked, but in my research I can't find an answer. I'm probably making a simple mistake.

I would like to run a Java class locally with Docker, inside a container. Below is my Dockerfile:

Dockerfile

FROM maven:3.5.2-jdk-8

COPY src /src

RUN javac src/java/com/Main.java
CMD java src/java/com/Main

I then run these commands in order:

docker build -t my_image_6_26_19:latest .
docker run -it my_image_6_26_19:latest

The build command runs fine, but the run command throws the following error:

Error: Could not find or load main class src.java.com.Main

I have reviewed the following questions on SO, but no answers seem to work (or maybe I didn't catch the solution):

When I build the container, through some debugging (RUN ls /src/java/com) I can see that a file Main.class is being created. I'm not sure why that file can't be found. Additionally, I have tried changing the last line of my Dockerfile to CMD java src/java/com/Main.class, but no luck.

Daniel
  • 2,345
  • 4
  • 19
  • 36

2 Answers2

5

If Main doesn't have a package try:

 CMD java -classpath src/java/com Main

if it does have a package (e.g. com, perhaps?) try:

CMD java -classpath src/java com.Main
martijno
  • 1,723
  • 1
  • 23
  • 53
1

The second version in answer from @martijno is the corect one. I additionally recommend telling the compiler to write the output into another directory, e.g. bin:

RUN javac src/java/com/Main.java -d bin
CMD java -cp bin com.Main
t0r0X
  • 4,212
  • 1
  • 38
  • 34