#!/bin/bash
# 设置PostgreSQL的版本和下载路径
POSTGRESQL_VERSION="12.3"
DOWNLOAD_URL="https://ftp.postgresql.org/pub/source/v${POSTGRESQL_VERSION}/postgresql-${POSTGRESQL_VERSION}.tar.gz"
# 安装编译依赖
sudo apt-get update
sudo apt-get install -y build-essential zlib1g-dev libssl-dev libreadline-dev libbz2-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
# 创建PostgreSQL用户和组
sudo groupadd -r postgres
sudo useradd -r -g postgres postgres
# 创建安装目录和数据目录
sudo mkdir -p /opt/postgresql /var/lib/postgresql
sudo chown -R postgres:postgres /opt/postgresql /var/lib/postgresql
sudo chmod -R 700 /var/lib/postgresql
# 下载并解压PostgreSQL源码
cd /opt
wget "$DOWNLOAD_URL"
tar -zxvf "postgresql-${POSTGRESQL_VERSION}.tar.gz"
# 编译和安装PostgreSQL
cd "postgresql-${POSTGRESQL_VERSION}"
./configure --prefix=/opt/postgresql --bindir=/opt/postgresql/bin --datadir=/var/lib/postgresql --libdir=/opt/postgresql/lib --includedir=/opt/postgresql/include --sysconfdir=/opt/postgresql/etc --docdir=/opt/postgresql/doc --mandir=/opt/postgresql/man --enable-depend --enable-cassert --enable-debug --with-openssl --with-pam --with-ldap --with-libxml --with-libxslt --enable-thread-safety
gmake
sudo gmake install
# 配置环境变量
echo 'export PATH=/opt/postgresql/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
# 初始化数据库
/opt/postgresql/bin/initdb -D /var/lib/postgresql
# 启动PostgreSQL服务
/opt/postgresql/bin/pg_ctl -D /var/lib/postgresql -l logfile start
# 创建多实例目录和配置多实例
for PORT in 5433 5434; do
DATA_DIR="/var/lib/postgresql/${PORT}"
CONF_FILE="/opt/postgresql/etc/postgresql.conf.${PORT}"
echo "Creating instance for port ${PORT}..."
sudo mkdir -p "${DATA_DIR}"
sudo chown -R postgres:postgres "${DATA_DIR}"
sudo chmod -R 700 "${DATA_DIR}"
# 配置文件模板并修改端口
cp /opt/postgresql/etc/postgresql.conf "${CONF_FILE}"
sed -i "s/port = 5432/port = ${PORT}/" "${CONF_FILE}"
sed -i "s/data_directory = '\/var\/lib\/postgresql'/data_directory = '\/var\/lib\/postgresql\/${PORT}'/" "${CONF_FILE}"
sed -i "s/hba_file = '\/var\/lib\/postgresql\/hba.conf'/hba_file = '\/var\/lib\/postgresql\/${PORT}\/hba.conf'/" "${CONF_FILE}"
sed -i "s/ident_file = '\/var\/lib\/postgresql\/pg_ident.conf'/ident_file = '\/var\/lib\/postgresql\/${PORT}\/pg_ident.conf'/" "${CONF_FILE}"
评论已关闭