将MySQL连接到Spring Boot:通信失败

时间:2019-06-05 04:41:01

标签: mysql spring-boot docker docker-compose

我是docker compose的新手,想将mysql附加到我的spring boot应用程序。

我的撰写文件看起来

version: '3'

volumes:
   mysql_data:

services:
   ww-mysql:
      image: mysql:5.7
      volumes:
         - mysql_data:/var/lib/mysql
      ports:
         - 3306:3306
      environment:
         MYSQL_ROOT_PASSWORD: root
         MYSQL_DATABASE: ww
         MYSQL_USER: admin
         MYSQL_PASSWORD: admin

ww-app:
      build: .
      image: ww-app
      ports:
         - 8080:8080
      depends_on:
         - ww-mysql
      links:
         - ww-mysql

连接到mysql的应用程序属性

spring.datasource.url = jdbc:mysql://localhost:3306/ww?useSSL=false
spring.datasource.username = admin
spring.datasource.password = admin

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

我得到的错误

 2019-06-05 04:58:16.411 ERROR 6 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000319: Could not get database metadata
ww-app_1    | 
ww-app_1    | com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
ww-app_1    | 
ww-app_1    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

我很困惑。我在ubuntu 18上运行了mysql服务器

2 个答案:

答案 0 :(得分:0)

我看不到您在其中放置驱动程序类名称。 //-对于mysql 5 spring.datasource.driver-class-name = com.mysql.jdbc.Driver

//-对于mysql 8

spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

答案 1 :(得分:0)

将JDBC URL更改为

  

jdbc:mysql:// ww-mysql:3306 / ww?useSSL = false

收到该错误的原因是因为两者都在不同的容器中运行,所以您无法告诉Spring服务在其容器中查找MySql连接。