Premise: Even if the solution is oriented to your specifics it would be better to execute tests during target jar build phase
To execute tests on your Dockerfile you can do one of the following:
copy also source files on Dockerfile and execute maven test commands. Doing this you can also build your target jar directly on the Container and also you need maven to be installed on the Container.
copy just the target jar file and use it to execute your tests you need to include test-classes on the target jar. ( See at How can I include test classes into Maven jar and execute them? ).
Regardless the way you choose, you can modify your entrypoint to execute multiple commands. You can do it basically in 2 ways:
- (a) Creating a bash script that executes your commands( See at Multiple commands on docker ENTRYPOINT )
- (b) Using supervisord ( See at How to write a Dockerfile which I can start a service and run a shell and also accept arguments for the shell? ). This is a better solution in order to manage process related to the container life ( so the process with PID 1 ).
Example
Let's suppose you choose to copy all source files ( option 1 ) and use a bash
script ( option 1(a) ) to do it.
Create the command.sh file as follow in order to attach container to Spring application process even if mvn test will be executed:
#!/bin/bash
#Execute Spring application
CMD="java -jar target/app.jar"
$CMD &
SERVICE_PID=$!
#Execute Tests
mvn test
#Wait for Spring execution
wait "$SERVICE_PID"
Your Dockerfile will look like follow:
#Start from maven docker image
FROM maven:3.6.1-jdk-8-alpine
#Copy all sources
COPY . .
#Build ( because you want to execute tests after the spring boot application is started you should disable test during build phase )
RUN mvn install
#Start container
COPY commands.sh /scripts/commands.sh
RUN ["chmod", "+x", "/scripts/commands.sh"]
ENTRYPOINT ["/scripts/commands.sh"]