Spring Boot MySQL Docker原因:java.net.ConnectException:连接被拒绝(连接被拒绝)

时间:2019-09-18 09:24:53

标签: mysql spring-boot docker

与标题中一样:

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

这在一段时间之前对我有用,但是现在不幸了。 我执行的脚本包含:

MVN全新安装-> 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

和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

3 个答案:

答案 0 :(得分:0)

{localhost}对您而言Docker容器不是主机(您的Docker容器所在的主机)的localhost。基本上,它指向您的Docker容器本身,其中MySQL不存在。因此,当您将MySQL的3306端口映射到主机的3306端口时,必须指向您的MySQL实例或容器的主机。

我肯定会指出@LinPy建议的MySQL本身:

spring.datasource.url=jdbc:mysql://mysql-standalone:3306/grades

答案 1 :(得分:0)

这应该对某人有帮助。

请确保运行以下命令以使当前图像无效:

docker rmi -f <your image id>

version: '3.1'

services:

  db:
    image: mariadb:10.5.5
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=softeasydb
      - MYSQL_USER=root
      - MYSQL_PASSWORD=root
    volumes:
      - ./db:/var/lib/mysql
    ports:
      - 3306:3306
    networks:
      - common-network   

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080
    networks:
      - common-network
      
  api-users:
    build: .
    depends_on: 
      - db
    ports:
      - 9090:9090   
    environment:
      - SPRING_PROFILES_ACTIVE=docker
      - DATABASE_HOST=db
      - DATABASE_USER=root
      - DATABASE_PASSWORD=root
      - DATABASE_NAME=softeasydb
      - DATABASE_PORT=3306
      - SERVER_PORT=9090
    restart: always
    networks:
      - common-network

networks:
  common-network:
      driver: bridge

答案 2 :(得分:0)

在您的 docker-compose.yaml 中,您在 mysql-standalone 容器的端口映射中有一个拼写错误,您需要更改以下内容:

ports:
- "33061:3306"

ports:
- "3306:3306"