0

I'm having a problem in connection between my application to DB (in-spite of similarity) enter image description here

Dockerfile:

FROM openjdk:8
ADD target/DockerMyBlog.jar DockerMyBlog.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "DockerMyBlog.jar"]

docker-compose.yml

version: "3"
services:
  app-db:
    image: mysql:latest
    container_name: "my_db"
    environment:
      - MYSQL_ROOT_PASSWORD=hey
      - MYSQL_DATABASE=javastudy
      - MYSQL_USER=roman
      - MYSQL_PASSWORD=hey
    ports:
      - 3306:3306
  app:
    build: .
    container_name: "my_app"
    ports:
      - "8080:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:mysql://app-db:3306/javastudy?autoReconnect=true&useSSL=false
    depends_on:
      - app-db

Instead of "build: ." tried "image: dockermyblog:latest". No result.

application.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/javastudy
jdbc.username=roman
jdbc.password=hey

my_db is working. After "exec" I can create required tables in it. But can't launch my_app because of "Communication link failure".

What's wrong in my yml??

  • Change your jdbc.url property value to SPRING_DATASOURCE_URL or hard code the url in that env variable there. Docker creates a network and the container names can are resolved there routing the traffic to the right container – martin kimani May 20 '22 at 09:33
  • Hi Martin, could you explain what means "hard code the url in that env variable there".How should it looks like? – surleversant May 20 '22 at 10:21
  • I've inserted in application.properties (jdbc.url=SPRING_DATASOURCE_URL), it did not help. But there is a place in my program, where I also call DB over Conection and define URL as (public static final String URL = "jdbc:mysql://localhost:3306/javastudy";). So may be that is a problem, so I wanna try your second way. – surleversant May 20 '22 at 10:24
  • jdbc:mysql://my_db:3306/javastudy?autoReconnect=true&useSSL=false this is the correct jdbc url to use. Replace the ip with your container name the docker network will resolve to your db container ip. – martin kimani May 20 '22 at 12:25

1 Answers1

0

My guess is that 'localhost' is not a valid enpoint for a Docker container talking to another container running on the host in your application.properties. You can try and put it on IP address of the machine like so:

jdbc.url=jdbc:mysql://192.168.1.100:3306/javastudy

or

jdbc.url=jdbc:mysql://host.docker.internal:3306/javastudy
kenneth
  • 478
  • 4
  • 11