【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 [email protected]
  * [email protected] - PostgreSQL Cluster 15-mydatabase
     Loaded: loaded (/lib/systemd/system/[email protected]; 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/[email protected]
             |-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 [email protected] - PostgreSQL Cluster 15-ubiz>
  Mar 27 15:51:36 zh-ubds-pg01-hw8-deb12-zx-ser systemd[1]: Started [email protected] - 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 [email protected]

切回 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)
相关推荐
Ai 编码助手5 分钟前
可视化+智能补全:用Database Tool重塑数据库工作流
数据库
敲上瘾9 分钟前
MySQL基本查询
数据库·mysql·数据库开发·数据库架构·数据库系统
清幽竹客34 分钟前
redis数据结构-09 (ZADD、ZRANGE、ZRANK)
数据结构·数据库·redis
A~taoker39 分钟前
django扩展练习记录
数据库·django·sqlite
kngines42 分钟前
【PostgreSQL数据分析实战:从数据清洗到可视化全流程】金融风控分析案例-10.3 风险指标可视化监控
postgresql·数据分析·区块链·逾期率·不良贷款率·客户信用评分
敲上瘾1 小时前
MySQL数据库表的约束
linux·数据库·sql·mysql·数据库开发·数据库架构·数据库系统
努力的搬砖人.1 小时前
SQLite 转换为 MySQL 数据库
数据库·mysql·sqlite
2301_803297752 小时前
Shell编程值正则表达式和文本处理器
数据库·mysql·正则表达式
TDengine (老段)3 小时前
基于 TSBS 标准数据集下 TimescaleDB、InfluxDB 与 TDengine 性能对比测试报告
java·大数据·开发语言·数据库·时序数据库·tdengine·iotdb
TDengine (老段)3 小时前
TDengine 在金融领域的应用
大数据·数据库·物联网·金融·时序数据库·tdengine·涛思数据