I'm working with spring boot, hibernate & MySql. While running the application it is running well as per expectation . But while making the docker-compose file and running the app docker image with mysql docker image it gives this error.
Error com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure java.net.ConnectException: Connection refused.
private Connection createConnection() throws SQLException
{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost/database?autoReconnect=true&useSSL=false";
Connection connection = DriverManager.getConnection(mysqlUrl, "root", "root");
return connection;
}
Application.properties
spring.datasource.url=jdbc:mysql://localhost/database?autoReconnect=true&useSSL=false spring.datasource.username=root
spring.datasource.password=root
Please guide me how to tackle this.
docker-compose.yml
version: '3'
services:
docker-mysql:
image: mysql:5.7
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=database
- MYSQL_USER=root
- MYSQL_PASSWORD=root
ports:
- 3307:3306
app:
image: app:latest
ports:
- 8091:8091
depends_on:
- docker-mysql
Issue is due to reference of localhost in the jdbc url.
Below configuration should work.
**docker-compose.yml**
version: '3'
services:
docker-mysql:
image: mysql:5.7
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=database
- MYSQL_USER=root
- MYSQL_PASSWORD=root
ports:
- 3307:3306
app:
image: app:latest
ports:
- 8091:8091
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://docker-mysql:3306/database?autoReconnect=true&useSSL=false
depends_on:
- docker-mysql
This Docker forum discussion helped me when I was running into this error. For me it was a problem with cache and I didn't get the error after running docker-compose down --rmi all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With