简体   繁体   中英

Connection refused (Connection refused) while trying to connect between docker containers

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM