David B
David B

Reputation: 3571

Connecting non-container local PostgreSQL to local SpringBoot docker container

I have a local PostgreSQL instance running on a non-container instance and I am not sure if I am doing the configuration right in SpringBoot or in Docker. When running the SpringBoot application on the local profile that contains all necessary details to the local PostgreSQL instance, the boot-up is successful. However, when I do it via Docker, everything doesn't work up and returns this error instead when running the container locally.

Dockerfile

FROM openjdk:15-alpine

ENV DB_URL=jdbc:postgresql://localhost:5432/sampledb
ENV DB_USER=dbuser
ENV DB_PASS=dbpass

ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar

ENTRYPOINT [ "java", \
    "-jar", \
    "-Dspring.profiles.active=docker", \
    "-Dapp.database.url=${DB_URL}", \
    "-Dapp.database.user=${DB_USER}", \
    "-Dapp.database.pass=${DB_PASS}", \
    "/app.jar" ]

application-docker.properties

spring.datasource.url=${app.database.url}
spring.datasource.username=${app.database.user}
spring.datasource.password=${app.database.pass}

I use this command after building the Dockerfile:

docker run -it -p 8080:8080 <container_name>

Now the container console logs prints this error and I don't have any database connection.

2021-02-02 16:54:02.702 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.

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.
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:303) ~[postgresql-42.2.18.jar!/:42.2.18]
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51) ~[postgresql-42.2.18.jar!/:42.2.18]
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:225) ~[postgresql-42.2.18.jar!/:42.2.18]

I know I should have gone through setting PostgreSQL as a docker container. However, I need to PostgreSQL to be an external resource in the Kubernetes cluster.

Upvotes: 1

Views: 331

Answers (1)

paltaa
paltaa

Reputation: 3244

Okay, so assuming you are running the Postgres database in the same machine that is running the docker container, there is a special DNS that points to the localhost of the host which is: host.docker.internal. (Remember localhost in a docker container points to the same container)

So, spring.datasource.url=host.docker.internal should point to your host localhost and not the docker container.

Upvotes: 2

Related Questions