注释Dockerfile中WORKDIR指令后编译Java文件报错,原因何在?
Why
javac: file not found: welcome.java Happens When You Comment Out WORKDIR Great question—let's break down exactly what's going on here:
- The base
openjdk:7image uses/(the root folder) as its default working directory. When you comment outWORKDIR /usr/src/myapp, every subsequent command (RUN,CMD, etc.) runs from this root directory. - Your
COPY . /usr/src/myappline copies all files from your local build context into the/usr/src/myappfolder inside the container. That means yourwelcome.javafile lives at/usr/src/myapp/welcome.java, not in the root directory where yourjavaccommand is executing. - When you run
javac welcome.javafrom/, the compiler looks for the file in the current working directory (which is/), can't find it, and throws that "file not found" error.
Simple Fixes to Resolve This
You've got two easy ways to fix this issue:
- Restore the
WORKDIRline: This is the cleanest approach. Adding backWORKDIR /usr/src/myappsets the working directory for all following commands, soRUN javac welcome.javawill look for the file exactly where you copied it. - Use full paths in your commands: If you don't want to set a dedicated working directory, update your
RUNandCMDto reference the full path of your app files:
TheRUN javac /usr/src/myapp/welcome.java CMD ["java", "-cp", "/usr/src/myapp", "welcome"]-cpflag tells the Java runtime where to find the compiledwelcome.classfile.
Either solution will ensure javac can locate your source file and the Java runtime can find the compiled class to execute.
内容的提问来源于stack exchange,提问作者jyolsna
相关产品推荐
相关产品推荐

