gyc
gyc

Reputation: 4360

Build multi maven modules then copy JARs inside a docker image

I have a multi-modules project configured with maven.

/myProject
  /module1
    /target
    pom.xml
  /module2
    /target
    pom.xml
  pom.xml

The pom parent is building the submodules.

Using the com.spotify.dockerfile-maven-plugin I want to build all the modules, build a docker image and copy all the JARs inside that image.

The pom parent

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>myTest</artifactId>
    <name>test</name>
    <version>0.0.1</version>
    <packaging>pom</packaging>

    <modules>
        <module>module1</module>
        <module>module2</module>
    </modules>

</project>

If I put a Dockerfile at the root of /myProject, the plugin complains there is no Dockerfile for module1

FROM openjdk:8-jdk-alpine
ARG JAR_FILE
COPY ${JAR_FILE} /home/xyz/jars

maven plugin:

    <plugin>
        <groupId>com.spotify</groupId>
        <artifactId>dockerfile-maven-plugin</artifactId>
        <configuration>
            <repository>mytest</repository>
            <buildArgs>
                <JAR_FILE>target/${project.artifactId}-${project.version}.jar</JAR_FILE>
            </buildArgs>
        </configuration>
    </plugin>

This works fine with one module if I put the Dockerfile inside that module but how to do with multiple modules and only 1 Dockerfile?

Can I build the submodules and then the docker image with a single mvn clean install on the parent pom?

Maybe by creating a submodule only with a pom and the Dockerfile?

Upvotes: 4

Views: 4771

Answers (1)

Ryan Dawson
Ryan Dawson

Reputation: 12548

If the jars are dependencies for one executable then yes, you could just build that one executable with its dependencies declared in its pom.xml file. Maven should figure out which order to build the submodules in, so long as you don't create a cycle. As you suggest, you want to make it a submodule and not the root pom as the root pom is parent configuration that is inherited by other modules. Just put the plugin on that one submodule (in its pom.xml) and only give it the Dockerfile.

(If you think of this as a problem about having one executable depending on libraries in the same maven project then it's not really related to docker. You could ask the same question about a spring boot app using libraries in the same multi-module project. In a sense it just is that problem as the jar will get built together with its dependencies and copied into the docker image.)

Or if you mean that each jar for each submodule is an executable in itself (and I don't think you do) then you could create multiple docker images, each from its own Dockerfile, and then you can bundle and start them together if you want to with a docker-compose file.

Upvotes: 2

Related Questions