How can I build an executable jar file in a docker container using Maven?
A simplified example of what I am trying to solve.
Local repo layout:
Main:
package org.example;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>maven-troubleshooting</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<archive>
<manifest>
<mainClass>org.example.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Local machine workflow(working as expected):
mvn clean package
...[INFO] BUILD SUCCESS
java -jar target/maven-troubleshooting-1.0-SNAPSHOT.jar
Hello world!
Dockerfile:
FROM maven:3.8.6-openjdk-11
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY pom.xml /usr/src/app
COPY src /usr/src/app
Docker workflow:
docker build . -t simplified-mvn-troubleshooting
docker run -it simplified-mvn-troubleshooting bash
(now in the running container)
mvn clean package
...[INFO] BUILD SUCCESS
java -jar target/maven-troubleshooting-1.0-SNAPSHOT.jar
Error: Could not find or load main class org.example.Main
Caused by: java.lang.ClassNotFoundException: org.example.Main
What am I missing?
CodePudding user response:
I solved this after a few hours of trial and error. It appears Maven is pretty strict with directory structure. I changed my dockerfile to the below which solved the issue.
FROM maven:3.8.6-openjdk-11 AS build
COPY pom.xml .
COPY src /src
I can now package and run the jar all in the docker container directly after attaching to the container.