如何解决Docker中启动Fat Jar时无法访问Jar文件的问题?
Hey there, let's troubleshoot why your container can't locate that JAR file. This is a common issue, and usually boils down to path mismatches or missing files. Here are the steps to fix it:
1. Verify your local JAR file exists (and is in the right place)
Your Dockerfile copies build/libs/Dockerwizard.jar into the container, but first you need to make sure this file actually exists in your build context (the directory where you run docker build).
- Run this command in your terminal (from the same folder as your Dockerfile) to check:
ls build/libs/ - Double-check the filename spelling—Docker is case-sensitive! If your JAR is named
dockerwizard.jar(lowercase d), the container won't find it.
2. Confirm the JAR was copied into the container
Sometimes the COPY command might not work as expected (e.g., typos in the path). Let's inspect the built image to see if the JAR is present:
- Run this command to launch a temporary container and list the contents of
/opt/hello:docker run --rm -it myapp ls /opt/hello - If you don't see
Dockerwizard.jarin the output, fix your COPY command. Make sure the source path (build/libs/Dockerwizard.jar) is relative to your Dockerfile's location.
3. Fix minor issues in your docker run command
While this isn't causing the JAR error, your run command has a parameter order issue that might cause confusion later. The correct format for docker run puts options before the image name. Adjust it to:
docker run -it -p 18080:8080 myapp
Also, note your Dockerfile exposes port 80, but you're mapping to 8080—if your app actually listens on 8080, update the EXPOSE line in your Dockerfile to EXPOSE 8080 for clarity (this doesn't affect functionality, just documentation).
4. Rule out permission problems (less likely, but worth checking)
If the JAR is present but still unreadable, add a line to your Dockerfile to ensure it has read permissions:
FROM java:8-jre COPY config.yml /opt/hello/ COPY build/libs/Dockerwizard.jar /opt/hello/ WORKDIR /opt/hello RUN chmod +r Dockerwizard.jar # Add this line EXPOSE 80 CMD ["java", "-Xms128m", "-Xmx1500m", "-Dfile.encoding=UTF-8", "-jar", "Dockerwizard.jar", "server", "config.yml"]
Since the java:8-jre image uses root by default, this is usually unnecessary, but it's a quick fix if permissions are the culprit.
Start with step 1—most of the time, the issue is just a missing or misnamed JAR in the build context!
内容的提问来源于stack exchange,提问作者A.Dumas

