Home >Database >Mysql Tutorial >How to Fix \'Communications Link Failure\' in Spring Boot with Docker and MySQL?
Developers utilizing Spring Boot, Hibernate, and MySQL within a Docker environment may encounter a common issue resulting in this error message:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure java.net.ConnectException: Connection refused.
This error typically stems from an incorrect host reference in the JDBC URL. To resolve this, it's crucial to modify the JDBC URL to point to the correct database hostname within the Docker environment.
Here's a clear demonstration of the solution:
1. Docker Compose Configuration:
The provided docker-compose.yml file uses localhost as the host for the MySQL database container, which is incorrect within the Docker environment.
2. Corrected Docker Compose Configuration:
To rectify this, update the docker-compose.yml file as follows:
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
In this updated configuration, the host docker-mysql refers to the name of the MySQL container, which ensures proper connectivity within the Docker environment.
3. Update Spring Boot Application Configuration:
Remove the spring.datasource.url property from the application.properties file. Spring Boot will use the environment variable SPRING_DATASOURCE_URL to configure the JDBC URL.
By implementing these changes, the application should be able to establish a successful connection to the MySQL database in the Docker environment.
The above is the detailed content of How to Fix \'Communications Link Failure\' in Spring Boot with Docker and MySQL?. For more information, please follow other related articles on the PHP Chinese website!