Postgres could not connect to server

踩坑 Postgres 记录。

问题描述

开发时,在Rails根目录下,运行rake db:create, 报错:

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

终端输入:psql, 报同样的错。

开发环境: PostgreSQL 10.0 , Rails 5.1.4, Ruby 2.3.6, MacOS Sierra 10.12.3

解决方法

在stack overflow上, Postgres could not connect to server中给出了这样的解答:

终端运行:

rm /usr/local/var/postgres/postmaster.pid

原因是:👇

可惜,我运行后出现报错:

rm: /usr/local/var/postgres/postmaster.pid: No such file or directory

后面的FreePender 给出了另一个解释,提到这类问题可能是版本升级导致, 并给出了解答。

运行:

postgres -D /usr/local/var/postgres

找到原因了,是版本不兼容问题:

The data directory was initialized by PostgreSQL version 9.6, which is not compatible with this version 10.0.

运行:

rm -rf /usr/local/var/postgres && initdb /usr/local/var/postgres -E utf8

重新bundle, 终端运行:

rake db:create

Perfect!! 完美解决!

Thanks to FreePender for this solution.

参考

Postgres could not connect to server