Docker运行Java镜像报错:Could not find or load main class问题排查求助
Hey there! Let's break down why you're hitting that ClassNotFoundException and fix it step by step.
The Root Causes of Your Error
You've got two key issues in your Docker setup:
Incorrect
CMDcommand syntax
You're runningjava src/com/company/Main.java— this is wrong for two reasons:- When executing compiled
.classfiles, you need to use the full qualified class name (likecom.company.Main), not a file path with.javasuffix. The.javasuffix tells Java to try compiling source code, but you don't have the source files in your container, only the compiled class. - Even if you had source files, the
src/path doesn't exist in your container (you never copied it over).
- When executing compiled
Broken
COPYinstruction
You're copying just the singleMain.classfile to/app, but Java requires the full package directory structure (com/company/Main.class) to locate the class. Your current COPY command strips away that structure, so Java can't mapcom.company.Mainto the right file.
Fixed Dockerfile
Here's the corrected version with explanations for each step:
FROM openjdk:11 # Set /app as the working directory (all subsequent commands run here) WORKDIR /app # Copy the entire compiled output directory (which contains the com/ package structure) into /app # This preserves the com/company/Main.class path Java expects COPY out/production/DockerTestApp/ . # Run the app using the full qualified class name — Java will look for com/company/Main.class in the current classpath (/app) CMD ["java", "com.company.Main"]
How to Test It
Rebuild and run your image with these commands:
docker build -t hello-world:3.0 . docker run hello-world:3.0
Quick Tips to Avoid This in the Future
- Always verify your compiled class structure locally: Navigate to
out/production/DockerTestAppand you should see acomfolder inside — that's the root of your classpath. - If you switch to Maven/Gradle later, your compiled classes will live in
target/classes(Maven) orbuild/classes/java/main(Gradle) — adjust theCOPYpath accordingly. - You can confirm the full qualified class name of your Main class by running
javap com.company.Mainfrom the directory containing thecomfolder locally.
内容的提问来源于stack exchange,提问作者helloJava
相关产品推荐
相关产品推荐

