Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communications link failure , Spring Boot + MySql +Docker + Hibernate

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
like image 310
Lily Avatar asked Nov 15 '19 16:11

Lily


2 Answers

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
like image 64
Barath Avatar answered Oct 20 '22 01:10

Barath


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

like image 38
Barry Sweeney Avatar answered Oct 20 '22 02:10

Barry Sweeney