为了学习Docker,我创建了一个小的SpringBoot应用程序,可以创建/列出/更新用户.

我在端口5432上运行一个PostgreSQL数据库,在端口8081上运行我的应用程序.问题是,当我try 启动容器和我的应用程序时:

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.

我创建了一个网络并启动了容器,如下所示:

docker run --name postgres --network demo-network -p 5432:5432 -e POSTGRES_PASSWORD=admin -d postgres
docker run --network demo-network -p 8081:8081 -d myuser/demodocker

我的Spring Boot应用程序.属性:

server.port=8081
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=drop-and-create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
javax.persistence.schema-generation.scripts.action=drop-and-create

要解决什么问题才能让它发挥作用?

推荐答案

在您的Spring Boot应用程序.properties文件中,您已经配置了spring.datasource.url属性以使用localhost:5432连接到PostgreSQL.但是,当在不同的Docker容器中运行您的Spring Boot应用程序和PostgreSQL数据库时,您不能使用localhost来引用数据库容器.相反,您应该使用PostgreSQL容器的主机名或服务的名称(容器名称),如果它们位于同一Docker网络上.

以下是你可以修复它的方法:

  1. 更新您的Spring Boot application.properties文件:
server.port=8081
spring.datasource.url=jdbc:postgresql://postgres:5432/postgres  # Use "postgres" as the hostname
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

spring.datasource.url属性中,将localhost更改为postgres.这样,您的Spring Boot应用程序将使用容器名作为主机名连接到PostgreSQL容器.

  1. 确保这两个容器位于相同的Docker网络上,就像您已经对demo-network所做的那样.

  2. 使用更新后的配置运行您的Spring Boot应用程序容器:

docker run --network demo-network -p 8081:8081 -d myuser/demodocker

现在,您的Spring Boot应用程序应该能够使用主机名"postgres"连接到在"postgres"容器中运行的PostgreSQL数据库.这应该可以解决连接问题.

记得在对application.properties文件进行这些更改后重新构建和重新部署您的Spring Boot应用程序容器.

Java相关问答推荐

我们如何直接使用kerminldap服务票证来通过ldap进行身份验证并形成LDAP上下文

将具有多个未知字段的SON映射到Java POJO

错误:在Liferay7.4中找不到符号导入com.liferay.portal.kernel.uuid.PortalUUID;";

如何使用Maven和Spring Boot将构建时初始化、跟踪类初始化正确传递到本机编译

Java中实现的归并排序算法给出ArrayIndexOutOfBound异常

名称冲突具有相同的擦除

如何创建一个2d自上而下的移动系统,其中移动,同时持有两个关键是可能的处理?

由于 list 中的权限错误,Android未生成

使用htmlunit和java单击按钮

Java Telnet客户端重复的IAC符号

基于配置switch 的@Controller的条件摄取

从LineChart<;字符串、字符串和gt;中删除数据时出现特殊的ClassCastException;

一对多关系和ID生成

Android应用程序为错误的显示类型 Select 尺寸文件

Java 21中泛型的不兼容更改

JavaFX标签中的奇怪字符

持续时间--为什么在秒为负数的情况下还要做额外的工作?

JOOQ:批处理CRUD操作使用动态表定义,如何?

由于版本不匹配,从Java 8迁移到Java 17和Spring 6 JUnit4失败

使用StringBuilder和append方法创建字符串时Java字符串内部方法的问题