我在 Spring Boot 上有一个这样的 docker 文件
services:
postgres:
container_name: newlife
image: postgres
environment:
POSTGRES_USER: local
POSTGRES_PASSWORD: local
PGDATA: /data/postgres
volumes:
- postgres:/data/postgres
ports:
- "8081:8081"
networks:
- postgres
restart: unless-stopped
networks:
postgres:
driver: bridge
volumes:
postgres:
这就是应用程序
server:
port: 1101
spring:
datasource:
url: jdbc:postgresql://localhost:8081/online
username: local
password: local
jpa:
hibernate:
ddl-auto: create-drop
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: true
show-sql: true
main:
web-application-type: servlet
错误表示连接尝试失败,当我检查 Docker 日志时,当 Spring 尝试连接时,它会像此日志中那样突然关闭
2023-09-15 13:04:18 2023-09-15 06:04:18.507 UTC [1] LOG: starting PostgreSQL 15.4 (Debian 15.4-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
2023-09-15 13:04:18 2023-09-15 06:04:18.508 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
2023-09-15 13:04:18 2023-09-15 06:04:18.508 UTC [1] LOG: listening on IPv6 address "::", port 5432
2023-09-15 13:04:18 2023-09-15 06:04:18.512 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2023-09-15 13:04:18 2023-09-15 06:04:18.517 UTC [66] LOG: database system was shut down at 2023-09-15 06:04:18 UTC
2023-09-15 13:04:18 2023-09-15 06:04:18.521 UTC [1] LOG: database system is ready to accept connections
2023-09-15 13:09:18 2023-09-15 06:09:18.625 UTC [64] LOG: checkpoint starting: time
2023-09-15 13:09:22 2023-09-15 06:09:22.791 UTC [64] LOG: checkpoint complete: wrote 44 buffers (0.3%); 0 WAL file(s) added, 0 removed, 0 recycled; write=4.148 s, sync=0.007 s, total=4.169 s; sync files=12, longest=0.004 s, average=0.001 s; distance=252 kB, estimate=252 kB
2023-09-15 13:04:18 server stopped
2023-09-15 13:04:18
2023-09-15 13:04:18 PostgreSQL init process complete; ready for start up.
2023-09-15 13:04:18
我认为我配置正确还是我错过了什么?
我认为您遇到的问题是因为您如何设置网络。您将网络引用为
localhost
,但您正在名为“postgres”的自定义网桥中运行。 Spring应用程序中的localhost
指的是Spring应用程序本地的主机,如果它没有在同一网络中的Docker中运行,则它将无法到达。您可以在另一个 Docker 容器中运行 Spring,在同一个 compose 文件中定义它们并使用 Docker 的“神奇”DNS 属性,然后只需使用服务名称引用它:
url: jdbc:postgresql://postgres:5432/online
也可能是 PostgreSQL 默认在端口 5432 上运行,而您打开了 8081 并将其映射到 8081 而不是默认的 5432。如果您能澄清如何运行 Spring 应用程序,这将是一个更好的答案。