简体   繁体   中英

Spring Boot database connection does not work when in Docker

I have a SpringBoot application, that runs perfectly on Tomcat and connects to a Postgres database.

eg application.properties

# approval datasource
spring.datasource2.driver-class-name=org.postgresql.Driver
spring.datasource2.jdbc-url=jdbc:postgresql://localhost:5432/approval
spring.datasource2.username=postgres
spring.datasource2.password=

Next I have Dockerised the application:

Dockerfile

FROM openjdk:14
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} nexct-approval-service.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","/nexct-approval-service.jar"]

I can access a restful service in the application, however it is giving the following error:

org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

Everything is running on localhost and I plan to deploy this to a linux server where everying runs on the same host too.

Question

Why does docker seem to change the host access? How do I configure this so that it can access the database using docker?

Solution for Mac: Inside your docker container simply have the db host set to host.docker.internal . This will be forwarded to the host the docker container is running on. Reference

Solution for Linux: Actually what you really need to do is connect your container with Postgres running on host system, so for that we need to tell Docker to set network mode to host.

  docker run -it --network=host -p 8081:8081 --name containerName 'imageName'

Or using docker-compose.yml :

To start the containers just issue following command docker-compose up

version: '3.7'

services:

  configurator:
    container_name: 'nameOfContainer'
    image: 'imageName'
    network_mode: "host"
    ports:
      - "8081:8081"
    restart: on-failure

For further learning please follow the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM