首页 > 解决方案 > 无法从另一个 docker 容器连接到在 docker 中运行的 mysql

问题描述

我有一个运行 mysql 映像的 docker 容器,docker run 命令 -

docker run --name=mysql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root mysql/mysql-server:5.7

我可以从 localhost:3306 上的 SpringBoot 应用程序连接到该数据库,但是当我运行我的 springboot 应用程序 -docker run command-

docker run --name=myservice -d -p 3306:3306 -p 8888:8888 <image-id>

它无法启动,并且在检查我看到的日志时,出现以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
'liquibase' defined in class path resource 
[org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration
$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is 
liquibase.exception.DatabaseException: 
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

如何让我的 Spring Boot 应用程序连接到运行 mysql 的容器?

编辑:为我的应用程序添加我的 application.yml 文件的数据源部分:

spring:
datasource:
    url: jdbc:mysql://localhost:3306/<db-name>
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
jpa:
    show-sql: true
    hibernate:
        ddl-auto: none
h2:
    console:
        enabledt: true 

标签: mysqldocker

解决方案


通过在 docker run 命令中使用 --link mysql 并在我的 application.yml 中将数据源 url 从 'localhost:3306' 更改为 'mysql:3306' 使其工作,因为默认情况下 Docker 有一个 DNS,它可以按名称调用容器.因此,一旦通过抨击“mysql”容器为我的用户“root”为我的数据库中的所有 IP 添加了授予权限,我就能够在另一个容器中使用数据库启动我的服务。但是,对于更通用的解决方案,创建网络或使用 docker compose 似乎是一个更好的主意


推荐阅读