Dockerfile after build container doesn't work ''Could not find or load main class''

Yoo Coders!
have one issue with docker, when i create container and after build it,i want run him,but have this Error
can somebody resolve it ? :slight_smile:

Error: Could not find or load main class Main
Caused by: java.lang.NoClassDefFoundError: sk/wynny/Main (wrong name: Main)

My Dockerfile

FROM openjdk:17.0.1
RUN mkdir /apd

COPY out/production/docker2/sk/wynny/ /apd

WORKDIR /apd

CMD  java Main

My Main class is just Hello world in Java

I am not a Java programmer, but I think you should copy the whole package and not just one file. Then you can refer to the class with it’s full qualified name sk.wynny.Main

FROM openjdk:17.0.1
RUN mkdir /apd

COPY out/production/docker2/ /apd

WORKDIR /apd

CMD  java sk.wynny.Main

This does not seem to be a Docker issue, because you should do the same without a Docker container. So to say something which is related to Docker, I would suggest you try to avoid building on the host and copying it into a container, because it can be problematic. An app could work on your host and still not work in a container. This is how I would do it:

FROM openjdk:17.0.1
COPY src/ /src/
RUN javac /src/sk/wynny/Main.java -d /app
WORKDIR /app

CMD ["java", "sk.wynny.Main"]

Later, when your app becomes larger, you can use multi-stage build. Build the app in one container, and copy the generated files into an image.

FROM openjdk:17.0.1 as builder
COPY src/ /src/
RUN javac /src/sk/wynny/Main.java -d /app

FROM openjdk:17.0.1
COPY --from=builder /app /app
WORKDIR /app

CMD ["java", "sk.wynny.Main"]
1 Like

thanks working ,a lot of videos from youtube was like i write ,but this working fine :slight_smile: