简体   繁体   English

Spring Boot 容器无法连接到 My SQL 容器

[英]Spring Boot container cannot connect to My SQL container

I have read all questions related the issue and controlled all points.我已阅读与该问题相关的所有问题并控制了所有要点。 It seems everything is ok with my codes but it doesn't connect anyway.我的代码似乎一切正常,但无论如何都无法连接。 I got CONNECTION REFUSED error when I try to connect from container.尝试从容器连接时出现 CONNECTION REFUSED 错误。 (BTW. Everything is fine when I change URL and try to connect from localhost) (顺便说一句。当我更改 URL 并尝试从 localhost 连接时,一切都很好)

My java project我的java项目

spring:
  datasource:
   url: jdbc:mysql://mysqldb:3306/bootdb
   username: root
   password: root
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    hibernate:
      ddl-auto: update
    database-platform: org.hibernate.dialect.MySQL5Dialect
    generate-ddl: true

My docker-compose file我的 docker-compose 文件

version: "3"
services:
  mysqldb:
    image: mysql
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: bootdb
    networks:
      - testnetwork
  employee-jdbc:
    image: bago1/student:latest
    restart: always
    build: .
    ports:
      - 8080:8080
    networks:
      - testnetwork
    depends_on:
      - mysqldb
    links:
      - mysqldb
networks:
  testnetwork:

It successfully connects from my local host machine when I edit URL as当我将 URL 编辑为

url: jdbc:mysql://mysqldb:3306/bootdb
  1. DB works fine数据库工作正常
  2. They are on the same network他们在同一个网络上
  3. syntax is fine语法很好

Add the hostname field in your docker compose like this:在 docker compose 中添加hostname段,如下所示:

version: "3"
services:
  mysqldb:
    image: mysql
    hostname: mysqldb
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: bootdb
  employee-jdbc:
    image: bago1/student:latest
    restart: always
    build: .
    ports:
      - 8080:8080
    depends_on:
      - mysqldb
    links:
      - mysqldb

(Ps: don't need the add the networks field, the use of docker-compose creates automatically a network for your services) (ps:不需要添加networks字段,使用 docker-compose 会自动为您的服务创建网络)

(PS2: it's a good practice to use tag when using images (instead of using mysql:latest) ) (PS2:使用图像时使用标签是一个好习惯(而不是使用 mysql:latest))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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