Spring Boot cannot connect to MySQLand exits in Docker/Docker compose

前端 未结 2 1626
一整个雨季
一整个雨季 2020-12-06 23:13

Below is my application.properties file

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://loca         


        
2条回答
  •  难免孤独
    2020-12-06 23:35

    Containers in compose services can connect to other containers by using name, e.g. try to ping database container from spring-boot container.

    Check if you can ping database container

    docker-compose exec spring-boot-jpa-docker-webapp /bin/bash
    

    once you are in the shell (You may have to install ping in spring-boot container for testing only apt-get install iputils-ping or yum install depending on image container is based on)

    ping docker-mysql
    

    if ping is successful then it means you can connect to database

    replace database url in application.properties with

    spring.datasource.url=jdbc:mysql://docker-mysql:3306/test?autoReconnect=true
    

    Minimal Example for Mysql

    image: mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - "./volumes/database:/var/lib/mysql"
    

    Try following docker-compose

    version: "3.7"
    services:
      docker-mysql:
        image: mysql:latest
        command: --default-authentication-plugin=mysql_native_password
        restart: always
        ports:
          - "3306:3306"
        environment:
          - MYSQL_ROOT_PASSWORD=root
          - MYSQL_DATABASE=test
        volumes:
          - "./volumes/database:/var/lib/mysql"
        networks:
          - spring_net
      spring-boot-jpa-docker-webapp:
        image: springboot_docker
        ports:
          - "8080:8080"
        networks:
          - spring_net
    networks:
      spring_net:
    

提交回复
热议问题