在 Ubuntu 22.04 上安装 PostgreSQL 16

2025-05-25

在 Ubuntu 22.04 上安装 PostgreSQL 16

概述
PostgreSQL 16 是流行的开源关系数据库的最新主要版本。它包含许多新功能和改进,例如增强的监控功能、更高的性能、增强的逻辑复制、额外的服务器配置以及安全性改进。

在本教程中,我们将介绍如何在 Ubuntu 22.04 上安装 PostgreSQL 16,我们还将介绍一些基本配置,以允许远程连接、启用密码验证以及开始创建用户、数据库等。

先决条件
Ubuntu 22.04
使用 root 权限或 sudo 访问
权限sudo su进入 root 而不是 ubuntu(默认用户)

第1步 - 添加PostgreSQL存储库

首先,更新包索引并安装所需的包:

sudo apt update
sudo apt install gnupg2 wget nano
Enter fullscreen mode Exit fullscreen mode

添加 PostgreSQL 16 存储库:

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
Enter fullscreen mode Exit fullscreen mode

导入存储库签名密钥:

curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/postgresql.gpg
Enter fullscreen mode Exit fullscreen mode

更新软件包列表:

sudo apt update
Enter fullscreen mode Exit fullscreen mode

第 2 步 - 安装 PostgreSQL 16

安装 PostgreSQL 16 和 contrib 模块:

sudo apt install postgresql-16 postgresql-contrib-16
Enter fullscreen mode Exit fullscreen mode

启动并启用 PostgreSQL 服务:

sudo systemctl start postgresql
sudo systemctl enable postgresql
Enter fullscreen mode Exit fullscreen mode

检查版本并确保它是 Postgresql 16:
psql --version
你应该得到类似

psql(PostgreSQL)16.0(Ubuntu 16.0-1.pgdg22.04+1)

第 3 步 - 配置 PostgreSQL 16

编辑 postgresql.conf 以通过将 listen_addresses 更改为 * 来允许远程连接:

sudo nano /etc/postgresql/16/main/postgresql.conf
listen_addresses = '*'
Enter fullscreen mode Exit fullscreen mode

通过编辑 pg_hba.conf 将 PostgreSQL 配置为使用 md5 密码验证,如果您希望通过PGADMIN等进行远程连接,这一点很重要:

sudo sed -i '/^host/s/ident/md5/' /etc/postgresql/16/main/pg_hba.conf
sudo sed -i '/^local/s/peer/trust/' /etc/postgresql/16/main/pg_hba.conf
echo "host all all 0.0.0.0/0 md5" | sudo tee -a /etc/postgresql/16/main/pg_hba.conf
Enter fullscreen mode Exit fullscreen mode

重新启动 PostgreSQL 以使更改生效:

sudo systemctl restart postgresql
Enter fullscreen mode Exit fullscreen mode

允许 PostgreSQL 端口通过防火墙:

sudo ufw allow 5432/tcp
Enter fullscreen mode Exit fullscreen mode

第 4 步 - 连接到 PostgreSQL

以 postgres 用户身份连接:

sudo -u postgres psql
Enter fullscreen mode Exit fullscreen mode

为 postgres 用户设置密码:

ALTER USER postgres PASSWORD 'VeryStronGPassWord@1137';
Enter fullscreen mode Exit fullscreen mode

结论:
我们已经在 Ubuntu 上成功安装了 PostgreSQL 16,并执行了一些基本配置,例如启用远程连接、设置密码验证、创建数据库和用户。PostgreSQL 现在可以用于开发或生产工作负载了。

文章来源:https://dev.to/johndotowl/postgresql-16-installation-on-ubuntu-2204-51ia
PREV
付费工具的开源替代品
NEXT
使用 Windows Subsystem for Linux 的 Epic 开发环境