无法从Java应用程序连接到Postgres

时间:2018-06-20 20:23:45

标签: java postgresql docker yaml dropwizard

我正在使用Windows 10 Home Edition,并使用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做到这一点的最佳方法是什么?

1 个答案:

答案 0 :(得分: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文件已写入正确的凭据(我确定它具有正确的凭据,但是我需要在列表中写三点;)