首页 文章

从Springboot app连接到mysql容器

提问于
浏览
2

大家好 !

这是我的第一次,所以我会尽力做到最好 .

我想创建一个运行Springboot框架的应用程序,我想将它连接到嵌入MySQL的Docker容器(但是Spring引导应用程序没有在docker上运行)

所以我跟着这个post

我做了我的docker-compose:

db:
     image: mysql
  ports:
     - '3306:3306'
  environment:
     - MYSQL_ROOT_PASSWORD=secret
     - MYSQL_DATABASE=users
  volumes:
     - ../data:/var/lib/mysql

我用这个命令运行它:

docker-compose run --service-ports db

一切都很好,所以现在我在spring boot上更改了我的application.properties:

## Server Properties 
   server.port= 5000

   ## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
   spring.datasource.url= jdbc:mysql://127.0.0.1:3306/users?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
   spring.datasource.username= root
   spring.datasource.password= secret

   ## Hibernate Properties

   #The SQL dialect makes Hibernate generate better SQL for the chosen database

   spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
   spring.jpa.hibernate.ddl-auto = update

   ## Hibernate Logging
   logging.level.org.hibernate.SQL= DEBUG

   ## Jackson Properties
   spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS= false
   spring.jackson.time-zone= UTC

但是,当我运行我的应用程序时,我有这个错误:(:

引起:org.springframework.jdbc.CannotGetJdbcConnectionException:无法获取JDBC连接;嵌套异常是com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败

我在MacOS上...

我试着跟着callicoder的路线......

https://www.callicoder.com/spring-boot-spring-security-jwt-mysql-react-app-part-1/

谢谢你的帮助 :)

1 回答

  • 1

    问题是db容器没有在localhost上运行,而是在一个小型Linux VM中运行,因为你在MAC上 .

    因此,要连接到数据库,您需要使用运行容器的计算机的IP地址 . 为此,请运行命令 docker-machine ip default . 这将返回您将在连接URL而不是localhost中使用的IP地址:

    spring.datasource.url= jdbc:mysql://<docker-machine-ip>:3306/users?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
    

相关问题