You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Incorrect CMD command syntax
    You're running java src/com/company/Main.java — this is wrong for two reasons:

    • When executing compiled .class files, you need to use the full qualified class name (like com.company.Main), not a file path with .java suffix. The .java suffix 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).
  2. Broken COPY instruction
    You're copying just the single Main.class file 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 map com.company.Main to 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/DockerTestApp and you should see a com folder inside — that's the root of your classpath.
  • If you switch to Maven/Gradle later, your compiled classes will live in target/classes (Maven) or build/classes/java/main (Gradle) — adjust the COPY path accordingly.
  • You can confirm the full qualified class name of your Main class by running javap com.company.Main from the directory containing the com folder locally.

内容的提问来源于stack exchange,提问作者helloJava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:47:44