Home  >  Article  >  Database  >  Why Does My Dockerized Spring Boot App Get \'Communications Link Failure\' When Connecting to MySQL?

Why Does My Dockerized Spring Boot App Get \'Communications Link Failure\' When Connecting to MySQL?

DDD
DDDOriginal
2024-11-02 18:11:29298browse

Why Does My Dockerized Spring Boot App Get

Dockerized Spring Boot, MySQL, and Hibernate: Troubleshooting "Communications Link Failure"

When running a Spring Boot application with MySQL within a Docker container, it's possible to encounter the error "Communications link failure" due to connection issues between the app and the database. This can be resolved by ensuring that the correct database hostname is used in the application's configuration.

In the provided configuration, the createConnection method uses the localhost hostname in the JDBC URL. This refers to the host machine, which is not where the MySQL Docker image is running.

To fix the issue, the Docker Compose file should be modified to use the MySQL image's hostname in the Spring Boot application's environment configuration. Here's the updated Docker Compose file:

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

By specifying the environment variable SPRING_DATASOURCE_URL in the Spring Boot application's Docker image, the hostname of the MySQL container (docker-mysql) will be used in the JDBC connection. This resolves the communication issue and allows the application to connect to the database successfully.

The above is the detailed content of Why Does My Dockerized Spring Boot App Get \'Communications Link Failure\' When Connecting to MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn