Docker容器中的Spring Boot应用程序以及主机中的MySQL [英] Spring Boot application in Docker Container with MySQL in Host

查看:109
本文介绍了Docker容器中的Spring Boot应用程序以及主机中的MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Spring Boot 应用程序,我打算在 Docker 容器上运行并测试此应用程序,我已连接到 MySQL 在我的主机上.为此,我在 application.properties 中有一个属性,如下所示

I have a Spring Boot application that I'm planning to run on a Docker container and to test this application I'm connection to MySQL on my host machine. To do that I have a property in my application.properties as below

spring.datasource.url = jdbc:mysql://host.docker.internal:3306/flexapp

现在,当我执行 ./mvnw安装dockerfile:build 时,它尝试在构建 Docker镜像之前先构建应用程序.在构建过程中,它会显示

Now when I do ./mvnw install dockerfile:build it tried to build the application before building the Docker image. While it's building it says

原因:java.net.UnknownHostException:host.docker.internal:提供的节点名或服务名,或者未知

显然,它无法解析 host.docker.internal .

如何将 Docker 容器中的 Spring Boot 应用程序连接到主机中的 MySql 实例?我用谷歌搜索并尝试了很多解决方案,但似乎没有任何效果.

How do I connect my Spring Boot application in Docker container to the MySql Instance in my host machine? I googled and tried a lot of solution but nothing seems to work.

推荐答案

问题是正在执行一些试图连接数据库的测试.这些测试将由于无法解析 host.docker.internal 而失败.

The problem is that there are some tests being executed that are trying to connect to the database. Those tests will fail due to the unablity to resolve host.docker.internal.

标准解决方案是使用spring boot提供的一种方法来外部化配置:

The standard solution is to externalize configuration using one of methods that spring boot provides: Externalized Configuration.

特别是,一种方法是将 spring.datasource.url 设置为指向application.properties中的本地主机,并通过

In particular, one way is to set the spring.datasource.url to point to localhost inside application.properties and to override it inside the Dockerfile by passing

--spring.datasource.url= jdbc:mysql://host.docker.internal:3306/flexapp

到Dockerfile内部的Entrypoint或CMD指令.

To the Entrypoint or CMD instruction inside the Dockerfile.

这篇关于Docker容器中的Spring Boot应用程序以及主机中的MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆