#!/bin/bash
# 关闭selinux
sudo setenforce 0
sed -i 's/^SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
# 常量设置
export pgsql_version="16.1" # pgsql版本
export install_path="/pgsql/app" # 安装、操作目录
export data_path="/pgsql/data" # 数据保存目录
export pgsql_username="postgres" # 用户名
export systemctl_name="pgsql" # systemctl名称
# 安装依赖
echo "......正在安装依赖......"
yum install -y make gcc gcc-c++ libxml2 libxml2-devel lz4-devel lz4 readline-devel openssl openssl-devel libicu-devel
echo "......依赖安装完成......"
# 下载源代码
echo "......正在下载源码包......"
wget -P ${install_path} https://mirrors.tuna.tsinghua.edu.cn/postgresql/source/v${pgsql_version}/postgresql-${pgsql_version}.tar.gz
echo "......源码包下载完成......"
# 解压缩
echo "......正在解压缩源码包......"
cd ${install_path}
tar -zxf ${install_path}/postgresql-${pgsql_version}.tar.gz
echo "......源码包解压缩完成......"
# 编译安装
echo "......正在编译安装......"
${install_path}/postgresql-${pgsql_version}/configure --prefix=${install_path} --enable-debug --with-lz4 --with-openssl --with-libxml
cd ${install_path}/postgresql-${pgsql_version} && make && make install
echo "......编译安装完成......"
# 添加用户组和用户
echo "......正在添加用户组和用户......"
groupadd ${pgsql_username} && useradd -g ${pgsql_username} ${pgsql_username} -m
echo "......完成添加用户组和用户......"
# 配置环境变量
echo "......正在配置环境变量......"
echo "export PGHOME=${install_path}" >> /etc/profile
echo "export PGDATA=${data_path}" >> /etc/profile
echo "PATH=\$PATH:\$PGHOME/bin:\$PGHOME/bin" >> /etc/profile
export PGHOME=${install_path}
export PGDATA=${data_path}
export PATH=$PATH:$PGHOME/bin:$PGHOME/bin
echo "......配置环境变量完成......"
# 创建数据文件夹并移交所有权
echo "......正在创建数据文件夹......"
mkdir -p $data_path
chown postgres:postgres $data_path
echo "......完成创建数据文件夹......"
# 切换用户并初始化数据库
echo "......正在初始化数据库......"
su - ${pgsql_username}
initdb
echo "......完成初始化数据库......"
# 修改配置文件
sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/g" ${PGDATA}/postgresql.conf
sed -i "s/max_connections = 100/max_connections = 1000/g" ${PGDATA}/postgresql.conf
sed -i "s/shared_buffers = 128MB/shared_buffers = 4GB/g" ${PGDATA}/postgresql.conf
echo "host all all 0.0.0.0/0 md5" >> ${PGDATA}/pg_hba.conf
# 配置systemctl脚本
exit
echo "......正在配置systemctl脚本......"
cat>/usr/lib/systemd/system/${systemctl_name}.service<<EOF
[Unit]
Description=postgresql${pgsql_version}
[Service]
Type=forking
User=${pgsql_username}
Group=${pgsql_username}
ExecStart=${PGHOME}/bin/pg_ctl -D ${PGDATA} start
ExecReload=${PGHOME}/bin/pg_ctl -D${PGDATA} restart
ExecStop=${PGHOME}/bin/pg_ctl -D ${PGDATA} stop
[Install]
WantedBy=multi-user.target
EOF
echo "设置防火墙"
firewall-cmd --zone=public --add-port=5432/tcp --permanent
firewall-cmd --reload
systemctl daemon-reload
systemctl start ${systemctl_name}
systemctl enable ${systemctl_name}
systemctl status ${systemctl_name}
echo "......systemctl脚本配置完成......"
echo "......!!!脚本运行完成!!!......"
修改默认密码
psql
ALTER USER postgres PASSWORD 'postgres';