Spring Boot + MySQL + Docker Compose - Cannot make Spring Boot connect to MySQL

Steven :

I've been trying to set up a connection between a backend (runs on Spring Boot) container and a pre-built MySQL container. However, I cannot get it to connect. My docker compose file is:

version: '3.7'

services:

  test-mysql:
    image: mysql
    restart: always
    volumes:
      - db_data:/var/lib/mysql
    environment:
      MYSQL_DATABASE: testdb
      MYSQL_USER: test
      MYSQL_PASSWORD: test
      MYSQL_ROOT_PASSWORD: root

  backend:
    depends_on: 
      - test-mysql
    build: 
      context: backend
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    restart: always  

volumes:
  db_data: {}

my application.properties:

spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://test-mysql:3306/testdb?autoReconnect=true&failOverReadOnly=false&maxReconnects=10
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=test
spring.datasource.password=test

When I use docker-compose up, Spring Boot is not able to recognize the container name test-mysql. It throws: java.net.UnknownHostException

When I change it to an IP, it says connection refused. I have been looking everywhere and couldn't come with a fix. I hope anyone can help me out. Thank you!

CodeWalter :

You have to mention the backend mysql properties in the composer file like below,

backend:
depends_on: 
  - test-mysql
build: 
  context: backend
  dockerfile: Dockerfile
ports:
  - "8080:8080"
restart: always
environment:
        SPRING_DATASOURCE_URL: jdbc:mysql://test- 
           mysql:3306/testdbautoReconnect=true&failOverReadOnly=false&maxReconnects=10
        SPRING_DATASOURCE_USERNAME: test
        SPRING_DATASOURCE_PASSWORD: test
links:
  - test-mysql:test-mysql

If this wouldn't work try to create a common docker network and add it to your composer file like below,

backend:
depends_on: 
  - test-mysql
build: 
  context: backend
  dockerfile: Dockerfile
ports:
  - "8080:8080"
restart: always
environment:
        SPRING_DATASOURCE_URL: jdbc:mysql://test- 
           mysql:3306/testdbautoReconnect=true&failOverReadOnly=false&maxReconnects=10
        SPRING_DATASOURCE_USERNAME: test
        SPRING_DATASOURCE_PASSWORD: test
networks:
      -common-network

test-mysql:
image: mysql
restart: always
volumes:
  - db_data:/var/lib/mysql
environment:
  MYSQL_DATABASE: testdb
  MYSQL_USER: test
  MYSQL_PASSWORD: test
  MYSQL_ROOT_PASSWORD: root
networks:
      -common-network

#Docker Networks
networks:
    common-network:
        driver: bridge

#Volumes
volumes:
    dbdata:
        driver: local

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=385877&siteId=1