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

注释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:7 image uses / (the root folder) as its default working directory. When you comment out WORKDIR /usr/src/myapp, every subsequent command (RUN, CMD, etc.) runs from this root directory.
  • Your COPY . /usr/src/myapp line copies all files from your local build context into the /usr/src/myapp folder inside the container. That means your welcome.java file lives at /usr/src/myapp/welcome.java, not in the root directory where your javac command is executing.
  • When you run javac welcome.java from /, 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:

  1. Restore the WORKDIR line: This is the cleanest approach. Adding back WORKDIR /usr/src/myapp sets the working directory for all following commands, so RUN javac welcome.java will look for the file exactly where you copied it.
  2. Use full paths in your commands: If you don't want to set a dedicated working directory, update your RUN and CMD to reference the full path of your app files:
    RUN javac /usr/src/myapp/welcome.java
    CMD ["java", "-cp", "/usr/src/myapp", "welcome"]
    
    The -cp flag tells the Java runtime where to find the compiled welcome.class file.

Either solution will ensure javac can locate your source file and the Java runtime can find the compiled class to execute.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:01:37