Search code examples
javamysqlspring-bootdocker

Connecting a Dockerized Spring Boot app to a local MySQL Database


I'm creating a spring boot project that needs to connect to a mysql database. I'm using Docker to automatizate the process of deploying.

  1. I create the docker image with the nex command.

docker build -t <projectname>

This is the configuration of my application.properties

    spring.datasource.url = jdbc:mysql://localhost/<db>
    
    spring.datasource.password= ....
    
    spring.datasource.username= ....
    
    spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
    
    spring.jpa.show-sql=true
    
    spring.jpa.hibernate.ddl-auto=create
  1. When I run the docker file image I get the next error: docker build -t

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

When I run the jar of the project, the project works properly and connect to the database, but with the docker image I can not connect to my local databas


Solution

  • Instead of using "localhost" you need to use "host.docker.internal"