Docker MySQL - can't connect from Spring Boot app to MySQL database

Try this docker-compose.yml:

version: '3'
services:
  workaround-mysql:
    container_name: workaround-mysql
    image: mysql
    environment:
      MYSQL_DATABASE: workaround
      MYSQL_USER: springuser
      MYSQL_PASSWORD: admin
      MYSQL_ROOT_PASSWORD: admin
      MYSQL_ROOT_HOST: '%'
    ports:
      - "3308:3306"
    restart: always
  workaround:
    depends_on: 
      - workaround-mysql
    restart: always
    # will build ./docker/workaround/Dockerfile
    build: ./docker/workaround
    working_dir: /workaround
    volumes:
      - ./:/workaround
      - ~/.m2:/root/.m2
    expose:
      - "8080"
    command: "mvn clean spring-boot:run"

And update your application.properties to use the next JDBC connection url:

spring.datasource.url=jdbc:mysql://workaround-mysql:3306/workaround?serverTimezone=UTC&max_allowed_packet=15728640

It should work when both containers in the same docker-compose file, because docker-compose creates default network for containers, so they can resolve each other by name.


What you haven't tried so far is running both containers on the same Docker network.

First, forget about IP addressing - using it should be avoided by all means.

Second, launch both compose instances with the same Docker network.

Third, do not expose ports - inside bridge network all ports are accessible to running containers.

  1. Create global network

     docker network create foo
    
  2. Modify both compose files so that they use this network instead of creating each one its own:

     version: '3.5'
     services:
    
     ....
    
     networks:
       default:
         external: true
         name: foo
    
  3. Remove expose directives from compose files - inside one network all ports are exposed by default

  4. Modify connection strings to use default 3306 port instead of 3308

  5. Enjoy


In order for the service to connect with MySql through docker it has to be in same network, look into Docker network

But for better solution I would suggest you to write a single docker compose file for MySql and Spring boot.The reason is it will easily be linked when you do that.No need any other configuration.

version: "3"
services:
  mysql-service:
    image: mysql
    ports:
      - "3306:3306"
    environment:
      - MYSQL_DATABASE=db
      - MYSQL_USER=root
      - MYSQL_PASSWORD=pass
      - MYSQL_ROOT_PASSWORD=pass
  spring-service:
    image: springservce:latest
    ports:
      - "8080:8080"
    depends_on:
      - mysql-service