最重要的参考文档还是官网文档:https://www.postgresql.org/docs/18/installation.html
1、安装postgresql
参考文档:https://www.postgresql.org/download/linux/ubuntu/
在Ubuntu 24.04.2 LTS下多种方式安装软件,比较方便的是用apt。用apt有两种方式安装,一种是通过Ubuntu官方源直接安装(版本可能不是最新版本):
apt install postgresql
另一种方式是通过postgresql自己的Apt Repository(可以安装最新版本):
sudo apt install -y postgresql-common
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
sudo apt -y install postgresql-17
完成安装后,安装程序自动在Linux下创建postgres用户;自动初始化数据库,正常无需手动执行initdb初始化数据库;同时创建postgresql服务,默认已开机启动。
2、超级管理员登录
安装后的postgresql已启动,想访问数据库,需要身份认证。默认本地认证方式peer(这是postgresql默认的登录方式),可以用户名postgres登录,具体设置认证方式的配置文件是pg_hba.conf。文件位置在/etc/postgresql/版本/main/pg_hba.conf
cat /etc/postgresql/16/mian/pg_hba.conf
# 16版本可以看到主要默认配置如下,可以看到本地认证是peer,
# 默认本地主机是scram-sha-256加密密码认证,老版本中是md5,因为不安全不再使用
# 默认非本地主机不能访问
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer
local all all peer
host all all 127.0.0.1/32 scram-sha-256
host all all ::1/128 scram-sha-256
postgres是postgresql安装时生成的,密码我们并不知道。但是可以利用sudo -u来切换到切postgres用户,切换后无需密码即可通过psql命令行工具登陆系统,psql允许用户与数据库实例进行交互。
sudo -u postgres psql
3、创建用户给应用使用
如果数据库无需要远程访问,可以直接创建用户,并给予创建数据库权限,就可以供后续应用初始化并使用数据库了。
sudo -u postgres psql
# 创建用户并设置密码
create user testuser with password 'testpassword' CREATEDB;
# 创建数据库,并给testuser用户赋予此数据库所有权限
create database testdb;
grant all privileges on database testdb to testuser;
#列出数据库
\l
#退出psql
\q
如果需要通过远程服务器访问数据库,则需要修改pg_hba.conf,增加或修改如下:
host all all 0.0.0.0/0 scram-sha-256