Issue
I have a Java App which needs to connect to MySQL.
On providing url: jdbc:mysql://localhost:3306/<dbname>
I am able to build the Jar. I, however, want to run it on a Docker Container in a network where I also have a MySQL container with name mysqlindocker
running. To build the Jar I put in URL as jdbc:mysql://mysqlindocker:3306/<dbname>
which I hope would work on running inside the container. But I fail to do it because the build fails. My guess is that on my local machine Spring is not able to point to that db url.
How do I build a jar with URL as jdbc:mysql://mysqlindocker:3306/<dbname>
?
P.S. I would not prefer pointing to MySQL running on localhost.
Solution
I build the jar using mvn clean install. It fails on @Test void contextLoads(). 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 ?
- 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=...)
.
- 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
Answered By - davidxxx