【问题标题】:Unable to connect to Postgres from java application无法从 Java 应用程序连接到 Postgres
【发布时间】:2018-06-20 20:23:44
【问题描述】:

我使用的是 Windows 10 家庭版,并使用 Docker Toolbox 来安装 PostgreSQL。

我在 Docker Toolbox 中运行以下命令来启动数据库:

docker ​​run​​ --name ​​mydb_postgres​​ -p ​​5432:5432 ​​-e POSTGRES_PASSWORD=mydb​ ​-e​POSTGRES_USER=mydb -e POSTGRES_DB=mydb postgres

运行后,似乎有什么东西关闭了它,但从最后一行可以看出,它似乎是成功的。

当我运行docker ps -a 时,我可以看到容器已启动并正在运行。

日志

2018-06-19 20:53:20.430 UTC [38] LOG:  received fast shutdown request
waiting for server to shut down....2018-06-19 20:53:20.461 UTC [38] LOG:  
aborting any active transactions
2018-06-19 20:53:20.467 UTC [38] LOG:  worker process: logical replication launcher (PID 45) exited with exit code 1
2018-06-19 20:53:20.468 UTC [40] LOG:  shutting down
2018-06-19 20:53:20.913 UTC [38] LOG:  database system is shut down
 done
server stopped

PostgreSQL init process complete; ready for start up.

2018-06-19 20:53:21.013 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
2018-06-19 20:53:21.014 UTC [1] LOG:  listening on IPv6 address "::", port 5432
2018-06-19 20:53:21.095 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2018-06-19 20:53:21.266 UTC [65] LOG:  database system was shut down at 2018-06-19 20:53:20 UTC
2018-06-19 20:53:21.301 UTC [1] LOG:  database system is ready to accept connections

现在我正在尝试使用DropWizard 和配置.yml 文件启动连接到该数据库的服务器。

在它尝试连接的.yml 文件中:

url: "jdbc:postgresql://localhost:5432/mydb"

服务器启动时抛出的错误:

Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

有些人提到在 PostgreSQL 中将侦听端口更改为“*”,但我不确定这是否正确 - 如果是的话 - 使用 docker 执行此操作的最佳方法是什么?

【问题讨论】:

  • postgres 日志对此有何评论?这应该可以准确说明连接被拒绝的原因。
  • 这是您使用 VirtualBox 的旧工具箱还是 HyperV 上的新工具箱?当容器运行时,看看你是否可以telnet localhost 5432。或者看看你能不能docker exec my-db /bin/bash然后psql到db。

标签: java postgresql docker yaml dropwizard


【解决方案1】:

我使用以下命令运行 postgres 容器:

docker run --name mydb_postgres -p 5432:5432 -e POSTGRES_PASSWORD=mydb -ePOSTGRES_USER=mydb -e POSTGRES_DB=mydb --rm postgres

然后检查监听端口:ss -ltpn

State      Recv-Q Send-Q Local Address:Port  Peer Address:Port               
LISTEN     0      128    :::5432             :::*

我已经成功连接数据库了:

# psql -h localhost -p 5432 -Umydb -W  
Password for user mydb: 

psql (9.6.7, server 10.4 (Debian 10.4-2.pgdg90+1))  WARNING: psql major version 9.6, server major version 10.
       Some psql features might not work. Type "help" for help.

mydb=# 

我已经在 linux 上完成了测试。

对于您的问题,我会检查:

  1. Windows 防火墙规则(本地主机上的端口 5432 是否可达?)
  2. 您与数据库的连接是从同一个容器还是从另一个容器完成的?在第二种情况下,您需要链接它们
  3. yml 文件已写入正确的凭据(我确定它已写入,但我需要在列表中写入三点;)

【讨论】:

    猜你喜欢
    • 2015-03-19
    • 2023-03-14
    • 1970-01-01
    • 2019-07-30
    • 2020-12-07
    • 1970-01-01
    • 2021-07-14
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多