skip to Main Content

I have read all questions related the issue and controlled all points. It seems everything is ok with my codes but it doesn’t connect anyway.
I got CONNECTION REFUSED error when I try to connect from container. (BTW. Everything is fine when I change URL and try to connect from localhost)

My java project

spring:
  datasource:
   url: jdbc:mysql://mysqldb:3306/bootdb
   username: root
   password: root
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    hibernate:
      ddl-auto: update
    database-platform: org.hibernate.dialect.MySQL5Dialect
    generate-ddl: true

My docker-compose file

version: "3"
services:
  mysqldb:
    image: mysql
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: bootdb
    networks:
      - testnetwork
  employee-jdbc:
    image: bago1/student:latest
    restart: always
    build: .
    ports:
      - 8080:8080
    networks:
      - testnetwork
    depends_on:
      - mysqldb
    links:
      - mysqldb
networks:
  testnetwork:

It successfully connects from my local host machine when I edit URL as

url: jdbc:mysql://mysqldb:3306/bootdb
  1. DB works fine
  2. They are on the same network
  3. syntax is fine

2

Answers


  1. Add the hostname field in your docker compose like this:

    version: "3"
    services:
      mysqldb:
        image: mysql
        hostname: mysqldb
        ports:
          - "3306:3306"
        environment:
          MYSQL_ROOT_PASSWORD: root
          MYSQL_DATABASE: bootdb
      employee-jdbc:
        image: bago1/student:latest
        restart: always
        build: .
        ports:
          - 8080:8080
        depends_on:
          - mysqldb
        links:
          - mysqldb
    

    (Ps: don’t need the add the networks field, the use of docker-compose creates automatically a network for your services)

    (PS2: it’s a good practice to use tag when using images (instead of using mysql:latest) )

    Login or Signup to reply.
  2. Remove ports configuration of MySQL container and insert:

        expose:
          - 3306
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search