Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker compose: spring boot connection to mysql database refused

I'm pretty new to Docker and I need to startup my Angular/SpringBoot/MySQL project with docker-compose on the docker toolbox. I copied a docker yml file into my project which used the same technologies and changed the paths inside of it to match my project. However when I try docker-compose, it throws the following error:

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
[...] 84 common frames omitted
Caused by: java.net.ConnectException: Connection refused (Connection refused)

the docker-compose.yml looks like:

version: '3'

services:
  database:
    image: mysql
    container_name: database
    environment:
      MYSQL_ROOT_PASSWORD: ****
      MYSQL_DATABASE: db_example
      MYSQL_USER: springuser
      MYSQL_PASSWORD: ****
    ports:
      - 3306:3306
    volumes:
      - db_exampleData:/var/lib/mysql

  springapi:
    image: openjdk:10-jre-slim
    container_name: springapi
    ports:
      - 8443:8443
    depends_on:
      - database
    volumes:
      - ./backend/target/backend-0.1.0.jar:/application.jar
    command: ["java", "-jar", "application.jar"]

  angular:
    image: nginx:alpine
    container_name: angular
    ports:
      - 4200:80
    depends_on:
      - springapi
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./frontend/my-app/dist/my-app:/usr/share/nginx/html

volumes:
  db_exampleData:

the application.properties:

spring.jpa.hibernate.ddl-auto=none
spring.jpa.open-in-view=false
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=****

server.port=8443

any suggestion would be helpful!

like image 801
Japhet Avatar asked Oct 16 '22 13:10

Japhet


1 Answers

you need to change your connecion like this:

jdbc:mysql://database:3306/db_example

and add this to your docker-compose under springapi service:

links:
   - database

on the other hand you may use wait-for-it.sh to check if DB is up by add a command section under springapi service:

command: ["path/to/wait-for-it.sh", "database:3306", "-t", "6000", "--", "YOUR ACTUAL COMMAND"]
like image 97
LinPy Avatar answered Oct 19 '22 01:10

LinPy