本文将详细介绍如何在Linux操作系统上安装PostgreSQL数据库。无论你是初学者还是有一定经验的运维人员,都能通过本教程顺利完成Linux安装PostgreSQL。我们将以CentOS 7(使用yum)和Ubuntu 20.04(使用apt)为例,涵盖从环境准备到基本使用的全过程。
在开始PostgreSQL Linux教程之前,请确保你的Linux系统已联网,并具有sudo权限。首先更新软件包索引:
# CentOS/RHELsudo yum update -y# Ubuntu/Debiansudo apt update && sudo apt upgrade -y 接着安装必要的编译工具和依赖包(如果计划源码安装):
# CentOSsudo yum groupinstall "Development Tools" -ysudo yum install readline-devel zlib-devel -y# Ubuntusudo apt install build-essential libreadline-dev zlib1g-dev -y 对于大多数用户,使用官方预编译仓库是最简单的方式,这也是Linux部署PostgreSQL的最佳实践。添加PostgreSQL官方yum/apt仓库:
# CentOS 7sudo yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm -y# Ubuntu 20.04sudo sh -c "echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list"wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -sudo apt update 安装PostgreSQL(以版本14为例):
# CentOSsudo yum install postgresql14-server postgresql14-contrib -y# Ubuntusudo apt install postgresql-14 postgresql-contrib-14 -y 如果你需要定制编译选项或使用最新版本,可以选择PostgreSQL源码安装。从官方下载页面获取源码包:
wget https://ftp.postgresql.org/pub/source/v14.5/postgresql-14.5.tar.gztar -xzf postgresql-14.5.tar.gzcd postgresql-14.5./configure --prefix=/usr/local/pgsqlmakesudo make install 源码安装后还需创建系统用户和数据目录,并初始化数据库,篇幅有限此处略过,详细可参考官方文档。
无论哪种安装方式,安装完成后都需要初始化数据库并启动服务:
# CentOS(使用yum安装后自动创建postgres用户)sudo /usr/pgsql-14/bin/postgresql-14-setup initdbsudo systemctl start postgresql-14sudo systemctl enable postgresql-14# Ubuntu(安装后自动初始化并启动)sudo systemctl start postgresqlsudo systemctl enable postgresql 默认情况下,PostgreSQL只允许本地连接。如果需要远程访问,修改配置文件postgresql.conf和pg_hba.conf。首先切换到postgres用户:
sudo -i -u postgres 编辑postgresql.conf:
vi /var/lib/pgsql/14/data/postgresql.conf # CentOS路径# 或 /etc/postgresql/14/main/postgresql.conf # Ubuntu路径# 修改 listen_addresses = "*" 编辑pg_hba.conf添加允许的IP段,例如:
host all all 192.168.1.0/24 md5 重启服务生效:sudo systemctl restart postgresql。
为postgres用户设置密码:
sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD "your_password";" 登录测试:psql -U postgres -h localhost。至此,你已成功在Linux上安装了PostgreSQL,并完成了基本配置。希望这篇Linux安装PostgreSQL教程对你有帮助!
本文由主机测评网于2026-02-15发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/20260225335.html