下面以 CentOS 7 / CentOS 8 为例,详细说明 从源码编译安装 PostgreSQL 的完整流程(以 PostgreSQL 16 为例,其他版本类似)。
# CentOS 7
yum groupinstall -y "Development Tools"
yum install -y \
readline-devel \
zlib-devel \
openssl-devel \
libxml2-devel \
libxslt-devel \
systemd-devel \
wget \
gcc \
make
# CentOS 8
dnf groupinstall -y "Development Tools"
dnf install -y \
readline-devel \
zlib-devel \
openssl-devel \
libxml2-devel \
libxslt-devel \
systemd-devel \
wget \
gcc \
make
cd /usr/local/src
wget https://ftp.postgresql.org/pub/source/v16.2/postgresql-16.2.tar.gz
tar -zxvf postgresql-16.2.tar.gz
cd postgresql-16.2
可到官网查看最新版本:
https://www.postgresql.org/ftp/source/
./configure \
--prefix=/usr/local/pgsql \
--with-openssl \
--with-readline \
--with-zlib \
--with-libxml \
--with-libxslt
常见参数说明:
| 参数 | 说明 |
|---|---|
| –prefix | 安装目录 |
| –with-openssl | 启用 SSL |
| –with-readline | 支持命令行历史 |
| –with-zlib | 压缩支持 |
| –with-libxml | XML 支持 |
make -j$(nproc)
make install
安装完成后,二进制文件位于:
/usr/local/pgsql/bin
出于安全考虑,不要使用 root 运行 PostgreSQL。
useradd -r -m -s /bin/bash postgres
mkdir -p /usr/local/pgsql/data
chown -R postgres:postgres /usr/local/pgsql
su - postgres
/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
/usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l logfile start
/usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data stop
编辑 /etc/profile 或 ~/.bashrc:
export PATH=/usr/local/pgsql/bin:$PATH
export PGDATA=/usr/local/pgsql/data
生效:
source /etc/profile
vim /etc/systemd/system/postgresql.service
内容如下:
[Unit]
Description=PostgreSQL database server
After=network.target
[Service]
Type=forking
User=postgres
Group=postgres
Environment=PGDATA=/usr/local/pgsql/data
ExecStart=/usr/local/pgsql/bin/pg_ctl start -D ${PGDATA}
ExecStop=/usr/local/pgsql/bin/pg_ctl stop -D ${PGDATA}
ExecReload=/usr/local/pgsql/bin/pg_ctl reload -D ${PGDATA}
Restart=on-failure
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable postgresql
systemctl start postgresql
systemctl status postgresql
postgresql.confvim /usr/local/pgsql/data/postgresql.conf
listen_addresses = '*'
port = 5432
pg_hba.confvim /usr/local/pgsql/data/pg_hba.conf
添加:
host all all 0.0.0.0/0 md5
systemctl restart postgresql
psql --version
su - postgres
psql
✅ 缺少依赖,根据提示安装对应 -devel 包即可。
netstat -tunlp | grep 5432
如果你需要:
可以继续告诉我,我可以给你定制方案。