没有 -h 标志,psql 无法连接

psql cannot connect without -h flag

我正在 运行ning psql 来自 Debian 8.7 终端,但无法弄清楚为什么它需要 -h 标志来执行。例如,如果我 运行 psql -U postgres 在终端上,我得到以下错误:

psql: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

但是,当我添加主机标志时,我能够连接:

psql -U postgres -h localhost

psql (9.4.10, server 9.6.2)
WARNING: psql major version 9.4, server major version 9.6.
         Some psql features might not work.
Type "help" for help.

postgres=#

这是什么原因?

看起来客户端和服务器对于应该创建 UNIX 套接字的目录有不同的想法。

连接到数据库时,运行

SHOW unix_socket_directories;

这将告诉您可以在哪个目录(或多个目录)中找到 UNIX 套接字。

您可以将目录名称与 -h 选项一起使用,或者将环境变量 PGHOST 设置为本地连接。

比如你得到的结果是/tmp(出厂默认),你可以使用

psql -h /tmp -U postgres