Dockerized Spring boot app connect to database docker image

人盡茶涼 提交于 2021-02-08 08:48:35

问题


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.

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

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"

The docker-compose file is the following:

version: '3'
    services:
        app1:
            image: "app1"
            ports:
                - "8731:8731"

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

More informations:

  1. My Oracle database is a docker container with the name : "ORA12201_1" and port 3769
  2. Inside the application.properties the database properties specified are correct since I am amble to start the application from IntelliJ

回答1:


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.

One of the recommended approach is User-defined networks

Create first a network

docker network create --driver bridge my_network

Run the applications

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 config

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


来源:https://stackoverflow.com/questions/60003840/dockerized-spring-boot-app-connect-to-database-docker-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!