How to resolve Error: Could not find or load main class error when using docker with springboot
Problem
When using Docker with Spring Boot projects, you might encounter the following error:
The core exception is:
Environment
- Java 1.8
- Spring Boot 2.3
- IntelliJ IDEA
- Docker 19
Debug
Dockerfile
Main Class
If you run the app with Gradle directly like this:
It works. However, if you run the Spring Boot Docker image directly without Kubernetes like this:
You get the error again:
Reason
The issue lies in the Dockerfile configuration, which causes the Spring Boot application to start with an incorrect classpath.
Solution
The problem is a typo in the Dockerfile. The classpath should point to /opt/app7
, not /opt/app8
. Here’s the corrected Dockerfile:
Pay attention to the last command in the Dockerfile:
The incorrect configuration was -cp /opt/app8
, while the correct configuration is -cp /opt/app7
. This ensures the application is installed in the correct directory.
Summary
In this post, we explored how to resolve the “Could not find or load main class” error when using Docker with Spring Boot. The key issue was an incorrect classpath in the Dockerfile, which was resolved by correcting the path from /opt/app8
to /opt/app7
. Ensuring the correct classpath is crucial for the successful deployment of Spring Boot applications in Docker containers.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!