Hey everyone, I’m new to Docker and I’m hitting a wall. Got a MySQL container up and running on port 3306, and I’ve put together a basic Spring Boot app. It works fine when I run it straight from IntelliJ, but when I try to use my Dockerfile to host it in Docker, I keep getting this ‘Failed to obtain JDBC Connection’ error. It’s driving me nuts!
It seems you’re encountering a common Docker networking issue. The problem lies in how your Spring Boot container is trying to resolve the MySQL hostname. In a Docker environment, ‘mysql’ won’t automatically resolve to your MySQL container.
To fix this, you need to ensure both containers are on the same Docker network. Create a custom network first:
docker network create patient-network
Then, run your MySQL container with:
docker run --name mysql --network patient-network -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql
For your Spring Boot container, modify the Dockerfile to include:
docker run --network patient-network your-spring-boot-image
This setup should allow your containers to communicate using the ‘mysql’ hostname. Remember to adjust other environment variables as needed when running the container.
I’ve been in your shoes, and I know how frustrating this can be. The issue likely stems from how Docker networking works. When you’re running the app in IntelliJ, ‘mysql’ resolves to localhost. In Docker, it’s trying to find a container named ‘mysql’.
Try changing your SPRING_DATASOURCE_URL to use the host.docker.internal instead:
This tells Docker to connect to the host machine’s localhost. Also, make sure your containers are on the same Docker network. You can create a custom network and add both containers to it:
docker network create mynetwork
docker run --network mynetwork --name mysql …
docker run --network mynetwork --name springapp …
If that doesn’t work, double-check your MySQL container is actually exposing port 3306 and that your Spring Boot app is waiting for MySQL to be ready before trying to connect. Good luck!