这是一篇 PostgreSQL 13 在 Linux 上安装的笔记,便于日后查询使用。数据库配置于 Debian 10 (Buster) 上,在配置的过程中,你可以参考官方文档

配置步骤

安装数据库

执行下面代码前,请确保可以执行 lsb-release。如果不存在,使用 apt 安装。

sudo apt install lsb-release

根据官方文档,执行:

# Create the file repository configuration:
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

# Import the repository signing key:
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

# Update the package lists:
sudo apt-get update

# Install the latest version of PostgreSQL.
# If you want a specific version, use 'postgresql-12' or similar instead of 'postgresql':
sudo apt-get -y install postgresql-13

配置数据库

PostgreSQL 做了一些默认的安全策略,只允许 lcoalhost 访问数据库。这些配置文件都位于 /etc/postgresql/13/main/ 中。

在调试阶段可以做一些修改,或使用 SSH 代理保证数据库的安全性。

  1. pg_hba.conf

    添加行:

    host	all		all		0.0.0.0/0		md5
    
  2. postgresql.conf

    修改行:

    listen_addresses = "*"	# Use '*' for all
    port = 1000				# 修改默认端口,建议大于 10000
    

修改默认密码

使用 postgres 账户执行 psql

su postgres

psql

由于在上一节中修改了 postgresql 的端口,需要使用 -p 参数。如

psql -p 1000

正常输出如下:

psql (12.4 (Debian 12.4-1.pgdg90+1))
Type "help" for help.

postgres=# 

查看数据库:

postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(3 rows)

查看数据库用户:

postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

修改默认用户密码:

postgres=# alter user postgres with password 'password';
ALTER ROLE

完成后用 systemctl 重启 postgresql 既可。然后使用 DataGrip 连接数据库。为了安全考虑,建议日常使用普通用户操作。

备份

一次性备份

由参考资料4,通过以下命令一次性备份数据库:

pg_dump –h localhost  -p  5432  -U  postgres -c  -C –f  kite-db.sql  db_name

恢复:

psql –h 127.0.0.1 -p 5432 -U postgres –f db_bak.sql

其他

修改数据库名称

ALTER DATABASE old_name RENAME TO new_name;

统计数据库大小

select pg_database_size('db_name');

优化数据库存储

vacuum full;

参考资料

[1] 如何在 Ubuntu 上安装和配置 PostgreSQL, Linux 中国

[2] Postgresql 配置文件详解, 博客园, Captains-Felix

[3] Postgresql 官方文档

[4] Postgresql的三种备份方式, CSDN 博客, 江天水一泓

本文改自 《上应小风筝-数据库配置文档》,原文是基于 PostgreSQL 12 版本的。作者就是我。