Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot MySQL Docker Caused by: java.net.ConnectException: Connection refused (Connection refused)

As in the title:

Caused by: java.net.ConnectException: Connection refused (Connection refused)

This worked for me sometime ago but now unfortunately not. Script that I execute contains:

mvn clean install -> docker-compose build -> docker-compose up

Dockerfile:

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

docker-compose.yaml

version: '3'

services:
  mysql-standalone:
    image: mysql:latest
    environment:
    - MYSQL_ROOT_PASSWORD=password
    - MYSQL_DATABASE=grades
    - MYSQL_USER=root
    - MYSQL_PASSWORD=password
    ports:
    - "33061:3306"
    volumes:
    - /data/mysql
  grades:
    image: grades
    build:
      context: ./
      dockerfile: Dockerfile
    depends_on:
    - mysql-standalone
    ports:
    - 8080:8080
    volumes:
    - /data/grades

And application.properties:

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/${MYSQL_DB:aws_eb_db}
spring.datasource.username=${MYSQL_USERNAME:root}
spring.datasource.password=${MYSQL_PASSWORD:password}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
like image 621
Mateusz Gebroski Avatar asked Oct 24 '25 18:10

Mateusz Gebroski


1 Answers

localhost for you Docker container is not the localhost of the host machine (the one where your Docker containers live). Basically it points to your Docker container itself, where MySQL doesn't live. So you have to point to your MySQL instance, or the host for your containers, as you are mapping the 3306 port of your MySQL to your host's 3306 port.

I would definitely point to the MySQL itself as @LinPy suggested:

spring.datasource.url=jdbc:mysql://mysql-standalone:3306/grades
like image 145
Hasan Can Saral Avatar answered Oct 26 '25 09:10

Hasan Can Saral