关于macos:如何检查PostgreSQL服务器Mac OS X的状态

How to check status of PostgreSQL server Mac OS X

如何判断我的Postgresql服务器是否正在运行?

我收到这条消息:

1
2
3
4
5
[~/dev/working/sw] sudo bundle EXEC rake db:migrate
rake aborted!
could NOT CONNECT TO server: Connection refused
    IS the server running ON host"localhost" AND accepting
    TCP/IP connections ON port 5432?

更新:

1
2
3
4
> which postgres
/usr/LOCAL/bin/postgres
> pg_ctl -D /usr/LOCAL/bin/postgres -l /usr/LOCAL/bin/postgres/server.log START
pg_ctl: could NOT OPEN PID file"/usr/local/bin/postgres/postmaster.pid": NOT a directory

更新2:

1
2
3
>pg_ctl -D /usr/LOCAL/var/postgres -l /usr/LOCAL/var/postgres/server.log START
server starting
sh: /usr/LOCAL/var/postgres/server.log: No such file OR directory


检查正在运行的进程的最简单方法:

1
ps auxwww | grep postgres

并查找看起来像这样的命令(您的版本可能不是8.3):

1
/Library/PostgreSQL/8.3/bin/postgres -D /Library/PostgreSQL/8.3/DATA

要启动服务器,请执行以下操作:

1
/Library/PostgreSQL/8.3/bin/pg_ctl START -D /Library/PostgreSQL/8.3/DATA -l postgres.log


您可以运行以下命令来确定postgress是否正在运行:

1
$ pg_ctl STATUS

您还需要设置PGDATA环境变量。

这是我在postgres的~/.bashrc文件中的内容:

1
2
3
4
5
6
export PGDATA='/usr/local/var/postgres'
export PGHOST=localhost
alias start-pg='pg_ctl -l $PGDATA/server.log start'
alias stop-pg='pg_ctl stop -m fast'
alias show-pg-STATUS='pg_ctl status'
alias restart-pg='pg_ctl reload'

要让它们生效,请记住如下所示:

1
$ . ~/.bashrc

现在,尝试一下,你应该得到这样的东西:

1
2
3
$ show-pg-STATUS
pg_ctl: server IS running (PID: 11030)
/usr/LOCAL/Cellar/postgresql/9.2.4/bin/postgres


你可能没有初始化postgres。

如果使用HomeBrew安装,则必须先运行init,然后才能使用其他内容。

要查看说明,请运行brew info postgres

1
2
3
4
5
6
7
8
9
10
# CREATE/Upgrade a DATABASE
IF this IS your FIRST install, CREATE a DATABASE WITH:
     initdb /usr/LOCAL/var/postgres -E utf8

TO have launchd START postgresql at login:
   ln -sfv /usr/LOCAL/opt/postgresql/*.plist ~/Library/LaunchAgents
Then to load postgresql now:    
   launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
Or, if you don't want/need launchctl, you can just run:
    pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

一旦你运行了它,它应该说:

Success. You can now start the database server using:

1
2
postgres -D /usr/LOCAL/var/postgres OR
pg_ctl -D /usr/LOCAL/var/postgres -l logfile START

如果仍有问题,请检查防火墙。如果你使用像HandsOff这样的好人!它被配置为阻止流量,然后您的页面将不会看到数据库。


从PostgreSQL 9.3开始,您可以使用命令pg_isready来确定PostgreSQL服务器的连接状态。

来自文档:

pg_isready returns 0 to the shell if the server is accepting connections normally, 1 if the server is rejecting connections (for example during startup), 2 if there was no response to the connection attempt, and 3 if no attempt was made (for example due to invalid parameters).


这取决于你的postgresql服务器的安装位置。您可以使用pg_ctl手动启动服务器,如下所示。

1
pg_ctl -D /usr/LOCAL/var/postgres -l /usr/LOCAL/var/postgres/server.log START


其他答案中建议的pg_ctl status命令检查postmaster进程是否存在,如果存在则报告它正在运行。这并不一定意味着它已准备好接受连接或执行查询。

最好使用另一种方法,例如使用psql运行简单查询并检查退出代码,例如psql -c 'SELECT 1',或使用pg_isready检查连接状态。