Dockerized Spring Boot应用程序连接到数据库Docker映像 [英] Dockerized Spring boot app connect to database docker image
问题描述
我有一个带有gradle的基本spring boot应用程序,该应用程序可以调用Oracle数据库,并且数据库属性在application.properties文件中指定.
I have a basic spring boot application with gradle which makes calls to an Oracle database and the database properties are specified in an application.properties file.
我使用插件"com.google.cloud.tools.jib"并使用以下命令创建了Spring Boot应用程序的Docker映像:
I created a Docker image of the spring boot application with the plugin "com.google.cloud.tools.jib" and using the following command:
./gradlew jibDockerBuild --image=app1
我有一个docker-compose文件,其中将映像指定为服务,并且我希望在运行命令"docker-compose up"时启动应用程序
I have a docker-compose file in which i specify the image as an service and i want the application to start when i run the command: "docker-compose up"
docker-compose文件如下:
The docker-compose file is the following:
version: '3'
services:
app1:
image: "app1"
ports:
- "8731:8731"
但是当我运行CMD中的"docker-compose up"命令时,我收到以下异常:
But when I hit the run the "docker-compose up" command in CMD I recieve the following exception:
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
更多信息:
- 我的Oracle数据库是一个名为"ORA12201_1"和端口3769的docker容器
- 在application.properties内,指定的数据库属性是正确的,因为我正在从IntelliJ启动应用程序.
推荐答案
您可以从IntelliJ连接而不会出现问题,因为容器将端口(3769)暴露给主机(您的PC),但是现在您尝试从一个主机进行连接将Docker容器转移到另一个容器.
容器不共享网络(隔离),因此您需要连接它们.
you can connect from IntelliJ without problem as the container exposes the port (3769) to the host (your PC), but now you are trying to connect from one Docker container to another.
The containers do not share the network (isolation) so you need to connect them.
推荐的方法之一是用户定义的网络
首先创建一个网络
docker network create --driver bridge my_network
运行应用程序
docker run -p 5432:5432 --network my_network -d --name=postgres postgres
docker run -p 5050:80 --network my_network -d --name=pgadmin dpage/pgadmin4
您可以通过以下方式验证它们是否在同一网络上有效运行
You can verify they are effectively running on the same network with
docker network inspect my_network
Spring Boot配置
您现在可以使用 host.docker.internal
作为主机名从另一个连接到另一个,例如在您的Spring Boot application.properties
You can now connect from one to another using host.docker.internal
as hostname, for example in your Spring Boot application.properties
spring.datasource.url=jdbc:postgresql://host.docker.internal:5432/postgres
这篇关于Dockerized Spring Boot应用程序连接到数据库Docker映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!