I am using Windows 11 x64, Java / JDK 19, Spring Boot 3, PostgreSQL 15.1 at my local PC. My Dockerfile
FROM amazoncorretto:19-alpine3.16-jdk
WORKDIR /app
ARG JAR_FILE=target/spring_jwt-1.0.0-SNAPSHOT.jar
COPY ${JAR_FILE} ./app.jar
EXPOSE 8081
ENTRYPOINT ["java","-jar","app.jar"]
My console log:
org.postgresql.util.PSQLException: Connection to 127.0.0.1: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:319) ~[postgresql-42.5.1.jar!/:42.5.1]
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.5.1.jar!/:42.5.1]
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:247) ~[postgresql-42.5.1.jar!/:42.5.1]
at org.postgresql.Driver.makeConnection(Driver.java:434) ~[postgresql-42.5.1.jar!/:42.5.1]
at org.postgresql.Driver.connect(Driver.java:291) ~[postgresql-42.5.1.jar!/:42.5.1]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-5.0.1.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:359) ~[HikariCP-5.0.1.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201) ~[HikariCP-5.0.1.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:470) ~[HikariCP-5.0.1.jar!/:na] at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-5.0.1.jar!/:na]
full: https://gist.github.com/donhuvy/0821da63081f4fd447111b7d1c6f2310
Docker run
docker run -p 8081:8081 latest:latest
How to run image with database connect?
CodePudding user response:
Localhost (127.0.0.1)
within a docker container refers to the container itself.
If you want to access anything on your actual machine, you need the network stack of the container to be able to access it, see container-networking.
For your example, the easiest way would be to use the host option:
If you use the host network mode for a container, that container’s network stack is not isolated from the Docker host (the container shares the host’s networking namespace), and the container does not get its own IP-address allocated. For instance, if you run a container which binds to port 80 and you use host networking, the container’s application is available on port 80 on the host’s IP address.
Also see: What does --net=host option in Docker command really do?
CodePudding user response:
Set
#spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/foo_db
spring.datasource.url=jdbc:postgresql://host.docker.internal:5432/foo_db