启动和停止 PostgreSQL 数据库服务器,通常使用pg_ctl。通常在我们的生产环境中,如果数据库主机发生意外停机或者由于计划内的硬件配置等操作停止了主机后,PostgreSQL 服务也将会停止,需要手动重启。因此,在生产环境中,采用编译安装 PostgreSQL 数据库后,建议配置系统 postgresql.service 服务,通过 systemctl 系统命令设置开机自动启动。
使用 systemctl 命令
配置 systemctl 服务
配置该服务之后,Redhat Linux 就可以使用 systemctl 系统控制命令来启动 PostgreSQL 数据库了。
-
使用 root 用户切换到 /usr/lib/systemd/system 目录,编辑 postgresql-12.service 文件,该文件默认不存在,需要手动编辑,如下:
vi postgresql-12.service
[Unit] Description=PostgreSQL database server After=network.target [Service] Type=forking User=postgres Group=postgres Environment=PGPORT=5432 Environment=PGDATA=/data/pg_data/ OOMScoreAdjust=-1000 ExecStart=/opt/pgsql/bin/pg_ctl start -D ${PGDATA} -s -o "-p ${PGPORT}" -w -t 300 ExecStop=/opt/pgsql/bin/pg_ctl stop -D ${PGDATA} -s -m fast ExecReload=/opt/pgsql/bin/pg_ctl reload -D ${PGDATA} -s TimeoutSec=300 [Install] WantedBy=multi-user.target
-
然后之下下列命令启用服务控制守护
[root@node1 pg_data]# systemctl daemon-reload
-
使用systemctl系统服务控制命令启动 postgresql
[root@node1 pg_data]# systemctl start postgresql-12.service
-
配置开机启动
[root@node1 pg_data]# systemctl enable postgresql-12.service
简介 systemctl 命令
-
使用systemctl 命令停止数据库
[sdedu@root:/root]#systemctl stop postgresql-12.service -
使用sytsemctl 命令启动数据库
[sdedu@root:/root]#systemctl start postgresql-12.service -
使用systemctl 命令启用数据库服务开机后自动启动
[sdedu@root:/root]#systemctl enable postgresql-12.service
使用 pg_ctl 命令
pg_ctl 命令为 PostgreSQL 服务端应用程序,可以用来初始化,启动和停止及控制 PostgreSQL 服务器。
pg_ctl 语法格式:
-
初始化数据库
pg_ctl init[db] [-D DATADIR] [-s] [-o OPTIONS] -
启动数据库
pg_ctl start [-D DATADIR] [-l FILENAME] [-W] [-t SECS] [-s] [-o OPTIONS] [-p PATH] [-c] -
关闭数据库
pg_ctl stop [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s] -
重启数据库
pg_ctl restart [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s] [-o OPTIONS] [-c] -
重新加载 postgresql.conf 或 pg_hba.conf 文件
pg_ctl reload [-D DATADIR] [-s] -
查看服务器是否在指定的数据目录运行
pg_ctl status [-D DATADIR] -
pg_ctl promote [-D DATADIR] [-W] [-t SECS] [-s]
-
pg_ctl logrotate [-D DATADIR] [-s]
-
pg_ctl kill SIGNALNAME PID
命令选项
-
-D, --pgdata=DATADIR:指定数据库相关文件的数据目录,如果省略,默认读取 PGDATA 环境变量
-
-s, --silent:静默输出,仅仅输出错误消息
-
-t, --timeout=SECS:指定等待操作完成的最大延时秒数。默认为 PGCTLTIMEOUT 环境变量的值,如果省略,默认60秒
-
-V, --version output version information, then exit
-
-w, --wait:等待操作完成,如果操作在延迟时间内未完成,pg_ctl 退出状态为非零
-
-W, --no-wait:不等待操作完成,不会提示数据库停止是否完成
启动 & 重启选项
-
-c, --core-files allow postgres to produce core files
-
-l, --log=FILENAME:将服务器日志输出追加到 filename中,也叫做服务器日志文件。如果该文件的 umask 设置为077,访问日志文件默认情况下其它用户不可读。
-
-o, --options=OPTIONS command line options to pass to postgres (PostgreSQL server executable) or initdb
-
-p PATH-TO-POSTGRES normally not necessary
启动 & 停止选项
-
-m, --mode=MODE:指定关闭数据库的模式,有三个选项,smart,fast,immediate,省略默认为fast
关库选项
- smart:smart模式会等待活动的事务提交结束, 并等待客户端主动断开连接之后关闭数据库
- fast:fast模式则会回滚所有活动的事务, 并强制断开客户端的连接之后关闭数据库(默认)
- immediate:模式立即终止所有服务器进程,当下一次数据库启动时它会首先进入恢复状态(不推荐使用)