Java app build fails with Mysql url pointing to a Docker Container Java app build fails with Mysql url pointing to a Docker Container docker docker

Java app build fails with Mysql url pointing to a Docker Container


I build the jar using mvn clean install. It fails on @Test voidcontextLoads(). If I comment that out, I am able to build the jar with db url point to my > docker container

In the frame of unit tests executed during the test phase of maven, the mysqlindocker hostname cannot be resolved :

jdbc:mysql://mysqlindocker:3306/<dbname>

Only containers inside the same docker network will resolve that.
And as these tests are executed outside the container (before to start it to be exact), they cannot access that network.

How to solve that ?

  1. Solving the root cause

In fact, the root cause of your build failure during the unit test execution is that you didn't define a jdbc url according to the target scope.
Indeed in the test phase of a maven build you generally want tests to use an in-memory database or a specific MySQL database. You don't want to use the same one than the which one used for the main application for consistent reasons (test reproducibility).Here a good practice is using another db instance for unit testing and that db should be accessible from the host that runs the build (localhost).
You can overriding the spring.datasource.url property for executed tests : either by defining an application-test.properties/yml file in src/test/resources or overriding the property directly in the test class @SpringBootTest(properties=...).

  1. Workaround

Note that if the MySQL db container port is published on the host where the build is executed, a (temporary) workaround would be to keep localhost in the url defined in spring.datasource.url for the build and to override it with the docker container name at runtime when you run the JAR as container endpoint :

java -jar myApp.jar --my-prop-url=jdbc:mysql://mysqlindocker:3306/dbname