3

Hello guys !

It's my first so I will try to make the best that I can.

I want to create an app which is running with Springboot framework and I would like to connect it to a docker container which embeds MySQL (but the spring boot app is not running on docker)

So I have followed this post

I have made my docker-compose:

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

and I run it with this command :

docker-compose run --service-ports db

All is fine, so now I change my application.properties on spring boot :

   ## 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

But When I run my app, I have this error :( :

Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

I'm on MacOS...

I tried to follow callicoder's course ...

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

Thanks for your help :)

MrADOY
  • 123
  • 1
  • 10

1 Answers1

2

The problem is that the db container is not running on localhost but rather inside a mini Linux VM since you are on a MAC.

Thus to connect to the database you need to use the IP address of the machine where the container is running. To do that run the command docker-machine ip default. This will return the IP address which you would use in the connection url rather than localhost:

spring.datasource.url= jdbc:mysql://<docker-machine-ip>:3306/users?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
yamenk
  • 46,736
  • 10
  • 93
  • 87
  • I have not docker machine, I have to create one ? – MrADOY Apr 16 '18 at 19:18
  • That used to be the case, but recent Docker for Mac versions use directly a hypervisor and not a vagrant VM. – dunni Apr 16 '18 at 19:19
  • 3
    Work with : `docker port database_db_1` output : `3306/tcp -> 0.0.0.0:3306` So I use : jdbc:mysql://0.0.0.0:3306/users?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false :) , Thx Bro – MrADOY Apr 16 '18 at 20:05