我有一个运行数据库的 Postgres 映像,并将其作为 Docker 容器运行,并且可以从 psql 连接到它,但是当我从应用程序服务器连接到它时,出现以下错误:
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.
cpo-platform-server-cpo-platform-1 | at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:342)
cpo-platform-server-cpo-platform-1 | at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:54)
cpo-platform-server-cpo-platform-1 | at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:263)
cpo-platform-server-cpo-platform-1 | at org.postgresql.Driver.makeConnection(Driver.java:443)
cpo-platform-server-cpo-platform-1 | at org.postgresql.Driver.connect(Driver.java:297)
cpo-platform-server-cpo-platform-1 | at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
cpo-platform-server-cpo-platform-1 | at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
cpo-platform-server-cpo-platform-1 | at doobie.util.transactor$Transactor$FromDriverManagerUnapplied.$anonfun$apply$19(transactor.scala:378)
cpo-platform-server-cpo-platform-1 | at doobie.util.transactor$Transactor$FromDriverManagerUnapplied.$anonfun$create$2(transactor.scala:347)
cpo-platform-server-cpo-platform-1 | at blocking @ doobie.util.transactor$Transactor$FromDriverManagerUnapplied.$anonfun$create$1(transactor.scala:347)
cpo-platform-server-cpo-platform-1 | at fromAutoCloseable @ doobie.util.transactor$Transactor$FromDriverManagerUnapplied.$anonfun$create$1(transactor.scala:347)
cpo-platform-server-cpo-platform-1 | at fromAutoCloseable @ doobie.util.transactor$Transactor$FromDriverManagerUnapplied.$anonfun$create$1(transactor.scala:347)
cpo-platform-server-cpo-platform-1 | at use @ doobie.util.transactor$Transactor$$anon$4.apply(transactor.scala:164)
从运行应用程序服务器的一个 Docker 容器连接到运行数据库的另一个 Docker 容器时,有什么需要注意的吗?我使用 docker compose 来启动它们,如下所示:
services:
my-app:
image: me/my-app-server:1.1-SNAPSHOT
ports:
- 127.0.0.1:9000:9000
environment:
configEnv: test
my-db:
image: my-db-postgres-test-container
ports:
- 127.0.0.1:5432:5432
启动后,我可以使用 psql 连接到数据库,但通过我的应用程序服务器连接失败。凭据、数据库服务器等均已正确配置,但仍然无法连接。
有任何想法吗?
当启动两个容器时,主机的公开端口不会跨容器公开。
在您的情况下,使用 postgres 容器的主机名
my-db
,而不是 localhost,从my-app
.