mysql - 无法从另一个 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
解决方案
通过在 docker run 命令中使用 --link mysql 并在我的 application.yml 中将数据源 url 从 'localhost:3306' 更改为 'mysql:3306' 使其工作,因为默认情况下 Docker 有一个 DNS,它可以按名称调用容器.因此,一旦通过抨击“mysql”容器为我的用户“root”为我的数据库中的所有 IP 添加了授予权限,我就能够在另一个容器中使用数据库启动我的服务。但是,对于更通用的解决方案,创建网络或使用 docker compose 似乎是一个更好的主意
推荐阅读
- python-3.x - Keras,Tensorflow:将两个不同的模型输出合并为一个
- python - 在终端和 Pycharm 中执行 Python 脚本的冲突
- pandas - 向 seaborn 中的子图添加误差线时出错
- android - How to autogenerate a Room database id without providing an id
- javascript - 从 API 发送和获取数据
- python - 尝试自动化浏览器时 Selenium 中的 ElementNotInteractableException
- python - 对csv文件Python 3.8的情绪分析
- android - 应用程序未使用应用程序 Google Play 应用程序英文标题在 Play 商店中搜索
- javascript - 为什么作为主体的 REST API 未定义?
- python - Python Hackerrank挑战给出了〜stdout没有响应〜错误