PostgreSQL是一个开源的对象-关系数据库系统,经过十多年的开发和改进,PostgreSQL已在可靠性、稳定性上已经十分强大,并且被应用的十分广泛。 很多云原生方向的产品例如开源镜像仓库Harbor、API网关Kong都使用了PostgreSQL。本文将介绍从源码编译安装PostgreSQL 13.5的具体过程。

安装环境和准备工作

两台CentOS 7服务器如下:

1192.168.100.151    node1
2192.168.100.152    node2

下载PostgreSQL的源码压缩包:

1curl -O -k https://ftp.postgresql.org/pub/source/v13.5/postgresql-13.5.tar.gz

解压缩源码:

1tar -zxvf postgresql-13.5.tar.gz

安装编译工具及相关依赖:

1yum install -y gcc bison gcc-c++ readline readline-devel zlib zlib-devel perl perl-devel systemd-devel

在这两台服务器上创建postgres用户:

1useradd postgres

创建postgresql相关目录:

1mkdir /home/postgres/data
2mkdir /home/postgres/init
3chown -R postgres:postgres /home/postgres

将使用/home/postgres/data作为数据库的数据目录。

编译安装PostgreSQL

进入到源码解压缩目录:

1cd postgresql-13.5

configure执行配置准备构建环境:

1./configure --with-pgport=5432 \
2  --prefix=/usr/local/pgsql \
3  --with-systemd \
4  --with-blocksize=8 \
5  --with-segsize=1 \
6  --with-wal-blocksize=8 \
7  --without-readline \
8  --datadir=/home/postgres/init

编译安装:

1make
2make install

初始化数据库

执行下面的命令对数据库进行初始化,数据库的初始化需要切换到postgres用户:

1su postgres
2/usr/local/pgsql/bin/initdb -D /home/postgres/data

创建systemd配置文件/etc/systemd/system/pgserver.service:

 1[Unit]
 2Description=PostgreSQL database server
 3Documentation=man:postgres(1)
 4
 5[Service]
 6Type=notify
 7User=postgres
 8ExecStart=/usr/local/pgsql/bin/postgres -D /home/postgres/data
 9ExecReload=/bin/kill -HUP $MAINPID
10KillMode=mixed
11KillSignal=SIGINT
12TimeoutSec=0
13
14[Install]
15WantedBy=multi-user.target

配置开机启动并启动PostgreSQL:

1systemctl enable pgserver --now

默认使用postgres用户可以本机登录到数据库:

1cd /usr/local/pgsql/bin
2./psql -p5432 -h127.0.0.1 -Upostgres
3psql (13.5)
4Type "help" for help.
5
6postgres=# 

修改数据库用户postgres的密码:

1postgres=#  \password

连接相关配置

修改/home/postgres/data/postgresql.conf配置文件,设置监听地址:

1listen_addresses = '*'

修改/home/postgres/data/pg_hba.conf(host-based authentication file)配置连接方式:

 1# TYPE  DATABASE        USER            ADDRESS                 METHOD
 2# "local" is for Unix domain socket connections only
 3local   all             all                                     trust
 4# IPv4 local connections:
 5host    all             all             127.0.0.1/32            trust
 6# IPv6 local connections:
 7host    all             all             ::1/128                 trust
 8# Allow replication connections from localhost, by a user with the
 9# replication privilege.
10local   replication     all                                     trust
11host    replication     all             127.0.0.1/32            trust
12host    replication     all             ::1/128                 trust
13
14
15host    all             all             192.168.100.0/24           md5

修改配置后重启数据库服务即可:

1systemctl restart pgserver

总结

本文在两台CentOS 7服务器上从源码编译安装了PostgreSQL,当前这两台服务器的PostgreSQL数据库是相互独立,它们之间没有任何关系。 下一节将介绍基于repmgr的postgresql主备高可用方案,将这两台PosgreSQL服务器配置成主备高可用架构。

参考