尝试使用dblink_connect连接到本地postgresql时出现SQL错误[08001],psql使用相同的url连接正常

vmdwslir  于 2023-03-12  发布在  PostgreSQL
关注(0)|答案(2)|浏览(345)

我从dblink_connect得到了奇怪的行为。
我使用docker运行postgresql的服务器,将5432Map到localhost:5433。
当我使用psql连接到它时,一切都很好

$ psql 'postgresql://pguser:pgpass@localhost:5433/mt5?sslmode=disable'
psql (14.4, server 10.22)

但是当我使用dblink_connect从另一个postgresql示例连接到它时,它失败了

psql 'postgresql://pguser:pgpass@localhost:5431/pgdb?sslmode=disable'
psql (14.4, server 14.3)
Type "help" for help.

pgdb=# select dblink_connect('postgresql://pguser:pgpass@localhost:5433/mt5?sslmode=disable');
ERROR:  could not establish connection
DETAIL:  connection to server at "localhost" (127.0.0.1), port 5433 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (::1), port 5433 failed: Address not available
        Is the server running on that host and accepting TCP/IP connections?
ghg1uchk

ghg1uchk1#

我发现了错误的原因:由于两个示例都是Docker的,因此它们不能将对方视为本地主机:您必须使用他们所公开的内部网络的IP地址,如192.168.88.22:

pgdb=# select dblink_connect('postgresql://pguser:pgpass@192.168.88.22:5433/mt5?sslmode=disable');
 dblink_connect
----------------
 OK
(1 row)

我在问问题的时候发现了这个问题!我想这对其他人也有帮助。

nvbavucw

nvbavucw2#

如果您的docker-compose.yaml文件包含以下内容:

services:
  postgres:
    image: postgres:15
    environment:
      POSTGRES_USER: pguser
      POSTGRES_PASSWORD: pgpass
      POSTGRES_DB: mydb

那么你最好使用host:DockerServiceName语法,因为它不会改变(虽然你的192.168.88.22IP可能会改变)。

SELECT dblink_connect('host=postgres port=5432 dbname=mydb user=pguser password=pgpass');

如果不希望使用服务名称,则参数为hostaddr,如中所示:

SELECT dblink_connect('hostaddr=192.168.88.22 port=5432 dbname=mydb user=pguser password=pgpass');

(Be意识到存在与以此方式传递口令相关联的风险)。

相关问题