0
votes

Trying to establish connection from app container to mysql container in localhost, getting connection refused exception

We are taking a docker approach to call rest api services to adopt microservice approach. We are establishing connection between app container and mysql container While doing so we have written a docker-compose file created mysql container and application container, exposed ports for both containers. Following is command for running docker-compose file docker-compose up.

docker-compose.yml file

version: '3'

services: docker-mysql: image: mysql:latest container_name: mysql-server environment: - MYSQL_ROOT_PASSWORD=abc123 - MYSQL_DATABASE=fitapp - MYSQL_PASSWORD=root ports: - 3307:3306

spring-webap:
    build:
        dockerfile: Dockerfile
        context: .
    image: fitapp:1.0
    depends_on:
      - docker-mysql
    ports:
      - 8092:8080


spring-webap_1  | Caused by: java.net.ConnectException: Connection refused
1
What do you mean by to mysql container in localhost ? You have two container so spring-webap can not contact mysql-server on localhost. Can you please provide the database connection string you are using in your application? - cmoetzing
mysql container in localhost, i mean both container are in localhost system. Database conection string: spring.datasource.url = jdbc:mysql://docker-mysql:3307/fitapp - fire research
Thanks for the reply. As per suggestion we have moved mysql docker container to other machine in the same network and we tried to run code as mentioned by you and tried multiple times with some changes but we are getting same error. - fire research
I did not suggest to move your container to a different machine. What you need to do is make sure that your containers can speak to each other like @Avi already pointed out. Either you link them or you put them on the same virtual docket network. - cmoetzing

1 Answers

1
votes

From what I could see below will be your docker-compose.yml (have changed the password for better understanding)

version: '3'
services:
  docker-mysql:
    image: mysql
    ports:
        - "3301:3306"
    environment:
        - MYSQL_USER=root
        - MYSQL_DATABASE=fitapp
        - MYSQL_ROOT_PASSWORD=pass
        - MYSQL_PASSWORD=pass
  spring-webap:
    build:
      dockerfile: Dockerfile
      context: .
    image: fitapp:1.0
    depends_on:
      - docker-mysql
    ports:
      - 8092:8080

The spring application.properties / application.yml should be like below

    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://docker-mysql:3301/fitapp
    username: root
    password: pass

Check that, if you have given localhost in url it will not work as the MySql and Spring service are running in different container.It should be linked or in a same network