使用源码安装 PostgreSQL 12.5 主从集群

使用源码安装 PostgreSQL 12.5 主从集群

本文原文链接:https://blog.csdn.net/xzk9381/article/details/110385135

  • Postgresql 版本:12.5

  • 操作系统版本:CentOS Linux release 7.6.1810 (Core)

  • 主节点 IP:10.211.55.11

  • 从节点 IP:10.211.55.12

一、环境准备

以下操作均在两台机器中执行。

1. 下载源码包

PostgreSQL 12.5 版本源码包下载地址:https://ftp.postgresql.org/pub/source/v12.5/postgresql-12.5.tar.gz

下载完成后,在两台机器中创建如下目录:

mkdir -p /opt/postgresql_data/{
    
    data,logs}

2. 配置 yum 源

在机器中配置阿里 yum 仓库:

wget http://mirrors.aliyun.com/repo/Centos-7.repo -O /etc/yum.repos.d/CentOS7-Base-ali.repo
sed -i 's/$releasever/7/g' /etc/yum.repos.d/CentOS7-Base-ali.repo

安装 PostgreSQL 依赖包:

yum -y install readline-devel zlib-devel

3. 关闭防火墙和 SELinux

为了避免访问被拒绝,需要关闭防火墙和 SELinux:

扫描二维码关注公众号,回复: 12760589 查看本文章
systemctl stop firewalld && systemctl disable firewalld
setenforce 0 && sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config

4. 创建用户

PostgreSQL 建议使用 postgres 用户来管理,首先创建相应的用户和组:

groupadd postgres
useradd -g postgres -G postgres -d /home/postgresql postgres
echo postgres_admin | passwd --stdin postgres

将 /opt/postgresql_data 目录的属主和属组改为 postgres:

chown postgres.postgres -R /opt/postgresql_data/

二、安装主节点

1. 安装 PostgreSQL

在 10.211.55.11 中,解压 PostgreSQL 源码包:

tar zxf postgresql-12.5.tar.gz -C /opt

在解压后的目录中执行如下编译安装命令:

./configure --prefix=/opt/postgresql_data
make && make install

# 下面的命令可以安装 PostgreSQL 的第三方工具
cd contrib
make && make install

安装完成,在 /opt/postgresql_data 目录下会存储可执行文件和库文件:

[root@localhost ~]# tree -L 1 -d /opt/postgresql_data/
/opt/postgresql_data/
├── bin
├── data
├── include
├── lib
├── logs
└── share

6 directories

接下来在 postgres 用户下设置环境变量,将以下两行内容添加至 postgres 用户家目录下的 .bash_profile 文件中并使其生效:

export LD_LBRARY_PATH=/opt/postgresql_data/lib:$LD_LIBRARY_PATH
export PATH=/opt/postgresql_data/bin:$PATH

2. 初始化数据库

以下步骤使用 postgres 用户执行:

首先初始化 PostgreSQL,指定数据目录为 /opt/postgresql_data/data 目录:

initdb --locale=C -E UNICODE -D /opt/postgresql_data/data/

命令执行成功后会输出如下内容:

The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "C".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /opt/postgresql_data/data ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Asia/Shanghai
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

initdb: warning: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    pg_ctl -D /opt/postgresql_data/data/ -l logfile start

3. 修改配置文件

初始化完成后查看一下 /opt/postgresql_data/data 目录下的内容:

[postgres@localhost ~]$ ls /opt/postgresql_data/data/
base          pg_hba.conf    pg_notify     pg_stat      pg_twophase  postgresql.auto.conf
global        pg_ident.conf  pg_replslot   pg_stat_tmp  PG_VERSION   postgresql.conf
pg_commit_ts  pg_logical     pg_serial     pg_subtrans  pg_wal
pg_dynshmem   pg_multixact   pg_snapshots  pg_tblspc    pg_xact

其中主要配置文件是 postgresql.conf,远程访问权限配置文件是 pg_hba.conf。

首先修改 postgresql.conf 文件内容,修改如下配置项:

listen_addresses = '*'                     # 修改监听地址为 *
max_connections = 1000                     # 修改最大连接数为 1000
log_destination = 'stderr'                 # 去掉该配置项的注释
logging_collector = on                     # 去掉该配置项的注释,并将 off 修改为 on,代表开启日志记录
log_directory = '../logs'                  # 去掉该配置项的注释,并指定写入日志的目录
log_filename = 'postgresql-%Y-%m-%d.log'   # 去掉该配置项的注释,并指定日志名称的格式

接下里修改 pg_hba.conf 配置文件,添加如下行:

host    all             all             0.0.0.0/0               trust

这个代表允许所有用户在远程的任何机器上使用密码访问数据库。

4. 启动数据库

启动数据库有两种方式,一种是手动启动,另外一种是通过脚本启动。

4.1 手动启动

手动启动数据库需要使用 postgres 用户执行 pg_ctl 命令,执行命令时需要指定数据目录的路径,命令如下:

pg_ctl -D /opt/postgresql_data/data/ -l ../log/start_log start

-l 参数是将启动时的日志输出到指定的文件中

停止数据库只需要将 start 换成 stop 即可。

4.2 脚本启动

在 PostgreSQL 的源码包中,提供启动数据库的脚本命令,路径如下:

[postgres@localhost ~]$ ls /opt/postgresql-12.5/contrib/start-scripts/
freebsd  linux  macos

其中 linux 文件就是用于在 Linux 中启动服务的脚本。使用 root 用户将该脚本拷贝到 /etc/init.d 目录下并重命名为 postgresql:

cp -pr /opt/postgresql-12.5/contrib/start-scripts/linux /etc/init.d/postgresql
chmod u+x /etc/init.d/postgresql

修改脚本中的如下配置项:

# Installation prefix
prefix=/opt/postgresql_data

# Data directory
PGDATA="/opt/postgresql_data/data"

# Who to run the postmaster as, usually "postgres".  (NOT "root")
PGUSER=postgres

# Where to keep a log file
PGLOG="/opt/postgresql_data/logs/serverlog"

设置开机启动:

chkconfig --add postgresql

然后就可以使用脚本来控制服务器启停:

service postgresql start

本文原文链接:https://blog.csdn.net/xzk9381/article/details/110385135

5. 创建复制角色

使用 postgres 用户操作 PostgreSQL 创建一个用于主从复制的角色:

[postgres@localhost ~]$ createuser --replication -P -e replicator
Enter password for new role:
Enter it again:
SELECT pg_catalog.set_config('search_path', '', false);
CREATE ROLE replicator PASSWORD 'md5eb5c69398a31748cd75327d33bc1f52b' NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT LOGIN REPLICATION;

-P 选项用于设置密码;

-e 选项用于设置回显;

为这个角色设置远程访问权限,在 pg_hba.conf 文件中添加如下一行内容:

host    replication     replicator      10.211.55.12/24         md5

这个代表允许在 10.211.55.12 机器上使用 replicator 角色远程访问数据库执行复制操作。

重启数据库:

service postgresql restart

三、安装从节点

首先按照安装主节点的步骤,执行第 1 - 4 步。

然后停掉从节点的服务,将数据目录下的数据备份,然后清除。使用 postgres 用户执行 pg_basebackup 命令连接远程主节点进行备份:

pg_basebackup -h 10.211.55.11 -D /opt/postgresql_data/data/ -U replicator -P -v  -R -X stream -C -S pgstandby1
  • -h :指定作为主服务器的主机。
  • -D :指定数据目录。
  • -U :指定连接用户。
  • -P :启用进度报告。
  • -v :启用详细模式。
  • -R :启用恢复配置的创建:创建一个standby.signal文件,并将连接设置附加到数据目录下的postgresql.auto.conf
  • -X :用于在备份中包括所需的预写日志文件(WAL文件)。流的值表示在创建备份时流式传输WAL。
  • -C :在开始备份之前,允许创建由-S选项命名的复制插槽。
  • -S :指定复制插槽名称。

运行命令后会输出如下内容:

Password:
pg_basebackup: initiating base backup, waiting for checkpoint to complete
pg_basebackup: checkpoint completed
pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1
pg_basebackup: starting background WAL receiver
pg_basebackup: created replication slot "pgstandby1"
24591/24591 kB (100%), 1/1 tablespace
pg_basebackup: write-ahead log end point: 0/2000100
pg_basebackup: waiting for background process to finish streaming ...
pg_basebackup: syncing data to disk ...
pg_basebackup: base backup completed

备份过程完成后,会在data目录下创建了一个standby.signal文件,并将primary_conninfo写入postgresql.auto.conf文件:

[postgres@CentOS-2 data]$ cat postgresql.auto.conf
# Do not edit this file manually!
# It will be overwritten by the ALTER SYSTEM command.
primary_conninfo = 'user=replicator password=admin host=10.211.55.11 port=5432 sslmode=disable sslcompression=0 gssencmode=disable krbsrvname=postgres target_session_attrs=any'
primary_slot_name = 'pgstandby1'

启动从节点服务:

service postgresql start

四、验证主从同步

首先在主节点中使用 postgres 用户查看复制插槽信息:

[postgres@localhost ~]$ psql -c "\x" -c "SELECT * FROM pg_replication_slots"
Expanded display is on.
-[ RECORD 1 ]-------+-----------
slot_name           | pgstandby1
plugin              |
slot_type           | physical
datoid              |
database            |
temporary           | f
active              | t
active_pid          | 12331
xmin                |
catalog_xmin        |
restart_lsn         | 0/3000148
confirmed_flush_lsn |

在从服务器中查看从服务器(WAL接收器进程)状态(进程和数据库):

进程状态:

[postgres@CentOS-2 ~]$ ps aux | grep walreceiver | grep -v grep
postgres 11225  0.0  0.0 318820  1868 ?        Ss   17:00   0:00 postgres: walreceiver   streaming 0/3000148

数据库状态:

[postgres@CentOS-2 ~]$ psql -c "\x" -c "SELECT * FROM pg_stat_wal_receiver;"
Expanded display is on.
-[ RECORD 1 ]---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
pid                   | 11225
status                | streaming
receive_start_lsn     | 0/3000000
receive_start_tli     | 1
received_lsn          | 0/3000148
received_tli          | 1
last_msg_send_time    | 2020-11-27 17:05:20.341976+08
last_msg_receipt_time | 2020-11-27 17:05:20.486497+08
latest_end_lsn        | 0/3000148
latest_end_time       | 2020-11-27 17:01:19.763682+08
slot_name             | pgstandby1
sender_host           | 10.211.55.11
sender_port           | 5432
conninfo              | user=replicator password=******** dbname=replication host=10.211.55.11 port=5432 fallback_application_name=walreceiver sslmode=disable sslcompression=0 gssencmode=disable krbsrvname=postgres target_session_attrs=any

接下来在主库中创建一个新的库:

[postgres@localhost ~]$ psql -c "create database repli_test;"
CREATE DATABASE
[postgres@localhost ~]$ psql -c "\l"
                             List of databases
    Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges
------------+----------+----------+---------+-------+-----------------------
 postgres   | postgres | UTF8     | C       | C     |
 repli_test | postgres | UTF8     | C       | C     |
 template0  | postgres | UTF8     | C       | C     | =c/postgres          +
            |          |          |         |       | postgres=CTc/postgres
 template1  | postgres | UTF8     | C       | C     | =c/postgres          +
            |          |          |         |       | postgres=CTc/postgres
(4 rows)

到从库中查看是否有这个库:

[postgres@CentOS-2 ~]$ psql -c "\l"
                             List of databases
    Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges
------------+----------+----------+---------+-------+-----------------------
 postgres   | postgres | UTF8     | C       | C     |
 repli_test | postgres | UTF8     | C       | C     |
 template0  | postgres | UTF8     | C       | C     | =c/postgres          +
            |          |          |         |       | postgres=CTc/postgres
 template1  | postgres | UTF8     | C       | C     | =c/postgres          +
            |          |          |         |       | postgres=CTc/postgres
(4 rows)

可以看到数据库信息已经同步,代表当前同步正常。

本文原文链接:https://blog.csdn.net/xzk9381/article/details/110385135

猜你喜欢

转载自blog.csdn.net/xzk9381/article/details/110385135
今日推荐