skip to Main Content

I have a docker compose which contains the following instructions :

version: '3.8'
services:
  mysql-standalone:
    container_name: marqueblanchebd
    image: marqueblanchebd:latest
    ports: 
      - "3307:3306"
    volumes:
      - data:/var/lib/mysql
        
  spring-boot:
    image: testmb
    container_name: mbwebservice
    ports:
    - "8091:8080"
    build:
      context: .                          
      dockerfile: Dockerfile 
    depends_on:
      - mysql-standalone 
    environment:
      SPRING_DATASOURCE_PASSWORD: ramses2021
      SPRING_DATASOURCE_URL: jdbc:mysql://marqueblanchebd:3307/marque_blanche?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
      SPRING_DATASOURCE_USERNAME: root
    volumes:
      - ./:/uploads/deployment
volumes:
  data:

when i run docker-compose up the following error occurs from my springboot project:
Caused by: java.net.ConnectException: Connection refused (Connection refused)

But when i put the default mysql port 3306 ("3306:3306") in docker-compose file, my springboot project connects itself successfully to my database container.
Here is my mysql dockerfile :

FROM mysql:latest

EXPOSE 3307
ENV MYSQL_DATABASE=marque_blanche
ENV MYSQL_ROOT_PASSWORD=ramses2021
ADD marque_blanche.sql /docker-entrypoint-initdb.d

2

Answers


  1. Chosen as BEST ANSWER

    I will suggest a simple way to solve the problem :

    Just insert this line in docker compose file for mysql service:

    environment:
      MYSQL_TCP_PORT: 3307 
    

    As it is said in this link


  2. Inside the docker network the service name marqueblanchebd will resolve to the containers IP. Given the SPRING_DATASOURCE_URL=jdbc:mysql://marqueblanchebd:3307/... the connection attempt is done to the <container_ip>:3307 however the database is listening on port 3306 hence the connection is refused. For the connection to work you’d need to configure the mysql service to listen on port 3307 instead of port 3306. The traffic does not transit out of the docker network to the host then from the host back into the docker network.


    I’d suggest not exposing the database to the host, you can remove the ports mappings from the mysql-standalone service e.g.:

    services:
      mysql-standalone:
        container_name: 'marqueblanchebd'
        image: 'marqueblanchebd:latest'
        expose: 
          - '3306'
        volumes:
          - 'data:/var/lib/mysql'
    

    … and configure the spring-boot service to use the default mysql-standalone service port:

      spring-boot:
        # ...
        environment:
          # ...
          SPRING_DATASOURCE_URL: jdbc:mysql://marqueblanchebd:3306/marque_blanche?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
          # ...
    

    This would isolate the database inside of the docker network.

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