运行Docker映像,无法连接数据库[已关闭]

ngynwnxp  于 2022-12-11  发布在  Docker
关注(0)|答案(2)|浏览(210)

Closed. This question does not meet Stack Overflow guidelines . It is not currently accepting answers.

This question does not appear to be about programming within the scope defined in the help center .
Closed 6 days ago.
Improve this question
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?

c2e8gylq

c2e8gylq1#

设定

#spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/foo_db
spring.datasource.url=jdbc:postgresql://host.docker.internal:5432/foo_db
ru9i0ody

ru9i0ody2#

Localhost(127.0.0.1)在一个docker容器内指的是容器本身。
如果你想访问实际机器上的任何东西,你需要容器的网络堆栈来访问它,参见container-networking
对于您的示例,最简单的方法是使用host选项:
如果对容器使用主机网络模式,则该容器的网络堆栈不会与Docker主机隔离(容器共享主机的网络名称空间),并且容器不会获得分配给它自己的IP地址。例如,如果运行绑定到端口80的容器并使用主机网络,则容器的应用程序可在主机IP地址的端口80上使用。
另请参阅:What does --net=host option in Docker command really do?

相关问题