Home > Software engineering >  docker network not working with spring boot and mysql
docker network not working with spring boot and mysql

Time:04-05

I am trying to run spring boot and mysql through docker, but there is a problem that I cannot connect.

docker-compose.yml

version: "3.7"

services:
  docker-mysql:
    container_name: docker-mysql
    image: mysql:8.0.28
    environment:
      MYSQL_USER: user
      MYSQL_PASSWORD: 1234
      MYSQL_ROOT_PASSWORD: 1234
    ports:
      - "3306:3306"
    networks:
      - docker-mysql

  app:
    build: .
    ports:
      - "8080:8080"
    depends_on:
      - docker-mysql
    container_name: app
    networks:
      - docker-mysql

networks:
  docker-mysql:

and spring boot application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://docker-mysql:3306?
    username: root
    password: 1234

when i run it using docker compose, you will get an error that you cannot connect to the db.

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:829) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:449) ~[mysql-connector-java-8.0.28.jar!/:8.0.28]
..
...

Caused by: java.net.NoRouteToHostException: No route to host
    at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
    at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:549) ~[na:na]
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]

CodePudding user response:

Your MySql username in the docker-compose file is user, but in your Spring config, it's root.

CodePudding user response:

I don' know this line is correct or not: url: jdbc:mysql://docker-mysql:3306?

Add this line at the end of your compose file:

driver: bridge

So, your docker-compose.yml file is:

version: "3.7"

services:
  docker-mysql:
    container_name: docker-mysql
    image: mysql:8.0.28
    environment:
      MYSQL_USER: user
      MYSQL_PASSWORD: 1234
      MYSQL_ROOT_PASSWORD: 1234
    ports:
      - "3306:3306"
    networks:
      - docker-mysql

  app:
    build: .
    ports:
      - "8080:8080"
    depends_on:
      - docker-mysql
    container_name: app
    networks:
      - docker-mysql

networks:
  docker-mysql:
    driver: bridge

https://docs.docker.com/compose/compose-file/compose-file-v3/#driver-1

  • Related