【PostgreSQL】- 1.3 PostgreSQL 创建数据库(初始化)

接 "【PostgreSQL】- 1.1 在 Debian 12 上安装 PostgreSQL 15",在本小节我们进行初始化。

创建集群

初始化与创建集群

切换用户为 postgres

复制代码
  ~# sudo -i -u postgres 

  ~$ mkdir /opt/pgdata/mydatabase
  ~$ pg_createcluster --datadir=/opt/pgdata/mydatabase 15 mydatabase
  Creating new PostgreSQL cluster 15/mydatabase ...
  /usr/lib/postgresql/15/bin/initdb -D /opt/pgdata/mydatabase --auth-local peer --auth-host scram-sha-256 --no-instructions
  The files belonging to this database system will be owned by user "postgres".
  This user must also own the server process.
  
  The database cluster will be initialized with locale "C".
  The default database encoding has accordingly been set to "SQL_ASCII".
  The default text search configuration will be set to "english".
  
  Data page checksums are disabled.
  
  fixing permissions on existing directory /opt/pgdata/mydatabase ... ok
  creating subdirectories ... ok
  selecting dynamic shared memory implementation ... posix
  selecting default max_connections ... 100
  selecting default shared_buffers ... 128MB
  selecting default time zone ... Asia/Shanghai
  creating configuration files ... ok
  running bootstrap script ... ok
  performing post-bootstrap initialization ... ok
  syncing data to disk ... ok
  Warning: systemd does not know about the new cluster yet. Operations like "service postgresql start" will not handle it. To fix, run:
  sudo systemctl daemon-reload
  Ver Cluster Port Status Owner    Data directory     Log file
  15  mydatabase  5432 down   postgres /opt/pgdata/mydatabase /var/log/postgresql/postgresql-15-mydatabase.log

在这里创建的 mydatabase 是一个 PostgreSQL 集群,它包含了运行一个特定版本的 PostgreSQL 所需的所有数据文件、配置文件和事务日志。命令中:

  • --datadir=/opt/pgdata/mydatabase 指定了新集群的数据目录位置。

  • 15 是 PostgreSQL 的版本号。

  • mydatabase 是这个新集群的名称。

    可以在最后看到 postgresql 集群及更多信息

    复制代码
    版本 15
    集群 mydatabase
    端口 5432
    状态 down
    拥有者 postgres
    数据目录 /opt/pgdata/mydatabase
    日志文件 /var/log/postgresql/postgresql-15-mydatabase.log

检查 postgresql 的新集群状态

复制代码
  ~# systemctl status postgresql@15-mydatabase.service
  * postgresql@15-mydatabase.service - PostgreSQL Cluster 15-mydatabase
     Loaded: loaded (/lib/systemd/system/postgresql@.service; enabled-runtime; preset: enabled)
     Active: active (running) since Wed 2024-03-27 15:51:36 CST; 2min 38s ago
    Process: 574 ExecStart=/usr/bin/pg_ctlcluster --skip-systemctl-redirect 15-mydatabase start (code=exited, status=0/SUCCESS)
   Main PID: 584 (postgres)
      Tasks: 6 (limit: 19051)
     Memory: 41.6M
        CPU: 228ms
     CGroup: /system.slice/system-postgresql.slice/postgresql@15-mydatabase.service
             |-584 /usr/lib/postgresql/15/bin/postgres -D /opt/pgdata/mydatabase -c config_file=/etc/postgresql/15/mydatabase/postgr>
             |-601 "postgres: 15/mydatabase: checkpointer "
             |-602 "postgres: 15/mydatabase: background writer "
             |-613 "postgres: 15/mydatabase: walwriter "
             |-614 "postgres: 15/mydatabase: autovacuum launcher "
             `-615 "postgres: 15/mydatabase: logical replication launcher "
  
  Mar 27 15:51:33 zh-ubds-pg01-hw8-deb12-zx-ser systemd[1]: Starting postgresql@15-mydatabase.service - PostgreSQL Cluster 15-ubiz>
  Mar 27 15:51:36 zh-ubds-pg01-hw8-deb12-zx-ser systemd[1]: Started postgresql@15-mydatabase.service - PostgreSQL Cluster 15-ubizd>

运行正常。注意这里区别与 "【PostgreSQL】- 1.1 在 Debian 12 上安装 PostgreSQL 15"初始化之前,现在为 active (running)

检查数据库

复制代码
  ~# sudo -i -u postgres
  ~$ psql
  psql (15.6 (Debian 15.6-0+deb12u1))
  Type "help" for help.
  
  postgres=# \l
                                             List of databases
    Name    |  Owner   | Encoding  | Collate | Ctype | ICU Locale | Locale Provider |   Access privileges
  ----------+----------+-----------+---------+-------+------------+-----------------+-----------------------
  postgres  | postgres | SQL_ASCII | C       | C     |            | libc            |
  template0 | postgres | SQL_ASCII | C       | C     |            | libc            | =c/postgres          +
            |          |           |         |       |            |                 | postgres=CTc/postgres
  template1 | postgres | SQL_ASCII | C       | C     |            | libc            | =c/postgres          +
            |          |           |         |       |            |                 | postgres=CTc/postgres
  (3 rows)
  
  postgres=#

创建新用户

在实际业务环境中,不建议使用默认的 postgres 用户进行所有操作,因为这可能带来安全风险。创建具有特定权限的单独用户(如 dbadmin)是一种更好的做法。

复制代码
  ~$ psql
  psql (15.6 (Debian 15.6-0+deb12u1))
  Type "help" for help.
  
  postgres=# CREATE USER dbadmin WITH PASSWORD 'my_password!';

配置外部访问权限

编辑pg_hba.conf文件以控制访问权限

编辑文件 pg_hba.conf

复制代码
  vim /etc/postgresql/15/mydatabase/pg_hba.conf

添加行,例如允许来自 172.16.x.x 网段的所有 IP 地址访问数据库

复制代码
  # TYPE  DATABASE        USER            ADDRESS                 METHOD  
  host    all             dbadmin         172.16.0.0/16           md5
  host    all             dbadmin         127.0.0.1/32            md5

pg_hba.conf 文件中,规则是按照它们出现的顺序进行评估的。这里给一个较完整的配置

复制代码
  # Database administrative login by Unix domain socket
  local   all             postgres                                peer
  
  # TYPE  DATABASE        USER            ADDRESS                 METHOD
  local   all             dbadmin                                 md5
  host    all             dbadmin         127.0.0.1/32            md5
  host    all             dbadmin         172.16.0.0/16           md5
  
  # "local" is for Unix domain socket connections only
  local   all             all                                     peer
  # IPv4 local connections:
  host    all             all             127.0.0.1/32            scram-sha-256
  # IPv6 local connections:
  host    all             all             ::1/128                 scram-sha-256
  # Allow replication connections from localhost, by a user with the
  # replication privilege.
  local   replication     all                                     peer
  host    replication     all             127.0.0.1/32            scram-sha-256
  host    replication     all             ::1/128                 scram-sha-256

编辑文件 postgresql.conf 文件中的 listen_addresses 设置,确保 PostgreSQL 服务监听所有接口

复制代码
  listen_addresses = '*'      # 监听所有接口  

重新加载 PostgreSQL 配置, 注意要切换到 root

复制代码
  ~# systemctl restart postgresql@15-mydatabase.service

切回 postgres, 继续为 dbadmin 赋权,授予该用户 CREATEDBCREATEROLE 权限,这样它就可以创建数据库和角色,但不能修改系统级别的配置或删除其他用户的数据库。

复制代码
  ~# sudo -i -u postgres
  ~$ psql
  psql (15.6 (Debian 15.6-0+deb12u1))
  Type "help" for help.
  
  postgres=# ALTER USER dbadmin CREATEDB CREATEROLE;
  ALTER ROLE

创建新数据库

注意这个例子数据库与集群同名为 mydatabase

复制代码
  ~# sudo -i -u postgres
  ~$ createdb -U dbadmin mydatabase
  Password:

再次查看数据库列表

复制代码
  ~$ psql
  psql (15.6 (Debian 15.6-0+deb12u1))
  Type "help" for help.
  
  postgres=# \l
                                             List of databases
    Name    |  Owner   | Encoding  | Collate | Ctype | ICU Locale | Locale Provider |   Access privileges
  ----------+----------+-----------+---------+-------+------------+-----------------+-----------------------
  postgres  | postgres | SQL_ASCII | C       | C     |            | libc            |
  template0 | postgres | SQL_ASCII | C       | C     |            | libc            | =c/postgres          +
            |          |           |         |       |            |                 | postgres=CTc/postgres
  template1 | postgres | SQL_ASCII | C       | C     |            | libc            | =c/postgres          +
            |          |           |         |       |            |                 | postgres=CTc/postgres
  mydatabase    | dbadmin  | SQL_ASCII | C       | C     |            | libc            |
  (4 rows)

已成功创建数据库。

dbadmin 进行验证

复制代码
  ~$ psql -U dbadmin -d mydatabase
  Password for user dbadmin:
  psql (15.6 (Debian 15.6-0+deb12u1))
  Type "help" for help.
  
  mydatabase=> SELECT version();
                                                      version
  -------------------------------------------------------------------------------------------------------------------
  PostgreSQL 15.6 (Debian 15.6-0+deb12u1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
  (1 row)
  
  mydatabase=>\q
  ~$

配置防火墙规则

配置防火墙规则规范对数据库服务器的网络访问,这里包含了 ssh 协议和 ipv6

复制代码
  ~# apt install ufw
  ~# ufw allow 5432/tcp
  ~# ufw allow ssh
  ~# ufw status verbose
  Status: active
  Logging: on (low)
  Default: deny (incoming), allow (outgoing), disabled (routed)
  New profiles: skip
  
  To                         Action      From
  --                         ------      ----
  5432/tcp                   ALLOW IN    Anywhere
  22/tcp                     ALLOW IN    Anywhere
  5432/tcp (v6)              ALLOW IN    Anywhere (v6)
  22/tcp (v6)                ALLOW IN    Anywhere (v6)
相关推荐
yume_sibai1 小时前
06-Rust Web 开发实战(Axum 框架 + 数据库 + JWT 认证 + 中间件 + 部署)
前端·数据库·rust
AugustRed2 小时前
Neo4j 图数据库原理 + 应用场景简单介绍
数据库·neo4j
Gl�ria2 小时前
Redis 高可用架构对比
数据库·redis
IpdataCloud3 小时前
高可用的IP数据接口平台有哪些?从可用性、P99延迟到离线部署的评估框架(含代码)
数据库·tcp/ip·ip
呆萌很3 小时前
MySQL 数据库和表的管理操作(命令行)
数据库·mysql
IvorySQL4 小时前
当PostgreSQL“听懂”MySQL——协议兼容层的设计与实战
数据库·人工智能·postgresql
这个DBA有点耶4 小时前
银行核心系统数据库迁移怎么选?6 步法+5 个避坑指南
数据库·安全·架构
风哥2号4 小时前
数据库教程FGMT31‑Linux平台MySQL9.7安装配置与版本升级
数据库
hanchenxing5 小时前
前端异步任务三方案:Celery vs Redis Stream vs BullMQ 实战对比消息队列
前端·数据库·redis·异步任务·方案对比
java_logo6 小时前
Docker 部署 Milvus:轻松搭建高性能向量数据库平台
数据库·docker·私有化部署·milvus·向量数据库·rag·轩辕镜像