Home > database >  Spring Boot MySQL docker containers
Spring Boot MySQL docker containers

Time:12-03

I have two containers, one with a Srping app and another with mysql. When I run the Spring app on my local machine, it successfully connects to my MySQL db running in a docker container. Once I spin up the Spring container I get a connection error, the app is unable to communicate with the MySQL container. How do I configure the Spring container to communicate with the db container? I've tried creating a bridge network to no avail. I believe my issue is spring.datasource.url=jdbc:mysql://localhost:3309/library but when I try with the network id the jar fails to build spring.datasource.url=jdbc:mysql://lms-network/library. I've been following this tutorial. docker image.

CodePudding user response:

There are couple of ways we can solve it.

Using docker-compose

Put both the containers in docker-compose file. Example:

version: "3"
services: 
  spring-boot-service:
    build:
      context: .
    ports:
      - 8080:8080
    environment:
      DB_HOST: mysql-db
      DB_NAME: library
      DB_USER: <user>
      DB_PASSWORD : <pwd>


  mysql-db:
    image: mysql
    ports:
      - 3306:3306
    environment:
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_DATABASE: <db_name>
      #... other properties

then in application.properties, use connection string as : spring.datasource.url=jdbc:mysql://${DB_HOST}:3306/${DB_NAME}

then use docker-compose up to run both containers together. This way they will share network through docker-compose.

Using host.docker.internal

When you run your spring boot app and mysql in separate containers, you can't refer the mysql database from localhost anymore as localhost means pointing to your container. Since mysql is running on your host machine, you can refer it by using host.docker.internal instead of localhost in connection string.

So you connection string should be

spring.datasource.url=jdbc:mysql://host.docker.internal:3309/library

  • Related