21.4. 配置示例
21.4.1. PostgreSQL 更改数据库位置
使用 Red Hat Enterprise Linux 时,PostgreSQL 存储其数据库的默认位置为
/var/lib/pgsql/data/
。这是默认情况下 SELinux 预期为它的位置,因此这个区域已为您使用 postgresql_db_t
类型进行适当标记。
数据库所在区域可根据个人环境要求或首选项进行更改,但务必要让 SELinux 知道此新位置;应相应地对其进行标记。本例介绍如何更改 PostgreSQL 数据库的位置,以及如何标记新位置,以便 SELinux 仍然能够根据其内容向新区域提供保护机制。
请注意,这只是一个示例,并演示 SELinux 如何影响 PostgreSQL。PostgreSQL 的综合文档不在本文档的讨论范围之内。详情请查看官方 PostgreSQL 文档。本例假定已安装了 postgresql-server 软件包。
- 查看
postgresql
的默认数据库位置的 SELinux 上下文:~]# ls -lZ /var/lib/pgsql drwx------. postgres postgres system_u:object_r:postgresql_db_t:s0 data
这将显示postgresql_db_t
,这是数据库文件的位置的默认上下文元素。此上下文必须手动应用到本示例中将使用的新数据库位置,才能正常工作。 - 为数据库的新位置创建一个新目录。在本例中,使用了
/opt/postgresql/data/
。如果您使用不同的位置,请将以下步骤中的文本替换为您的位置:~]# mkdir -p /opt/postgresql/data
- 执行新位置的目录列表。请注意,新目录的初始上下文是
usr_t
。该上下文不足以让 SELinux 为 PostgreSQL 提供保护机制。当上下文改变后,它将能够在新领域正常工作。~]# ls -lZ /opt/postgresql/ drwxr-xr-x. root root unconfined_u:object_r:usr_t:s0 data
- 更改新位置的所有权,以允许 postgres 用户和组访问。这会设置 SELinux 仍然会观察到的传统 Unix 权限。
~]# chown -R postgres:postgres /opt/postgresql
- 使用文本编辑器打开
/etc/systemd/system/postgresql.service
文件,并修改PGDATA
和PGLOG
变量以指向新位置:~]# vi /etc/systemd/system/postgresql.service PGDATA=/opt/postgresql/data PGLOG=/opt/postgresql/data/pgstartup.log
保存此文件并退出文本编辑器。如果/etc/systemd/system/postgresql.service
文件不存在,请创建该文件并插入以下内容:.include /lib/systemd/system/postgresql.service [Service] # Location of database directory Environment=PGDATA=/opt/postgresql/data Environment=PGLOG=/opt/postgresql/data/pgstartup.log
- 在新位置初始化数据库:
~]$ su - postgres -c "initdb -D /opt/postgresql/data"
- 更改数据库位置后,启动服务此时将失败:
~]# systemctl start postgresql.service Job for postgresql.service failed. See 'systemctl status postgresql.service' and 'journalctl -xn' for details.
SELinux 导致服务无法启动。这是因为新位置没有正确标记。以下步骤解释了如何标记新位置(/opt/postgresql/
),并正确启动 postgresql 服务: - 使用
semanage
工具为/opt/postgresql/
以及其中的任何其他目录/文件添加上下文映射:~]# semanage fcontext -a -t postgresql_db_t "/opt/postgresql(/.*)?"
- 这个映射被写入
/etc/selinux/targeted/contexts/files/file_contexts.local
文件:~]# grep -i postgresql /etc/selinux/targeted/contexts/files/file_contexts.local /opt/postgresql(/.*)? system_u:object_r:postgresql_db_t:s0
- 现在,使用
restorecon
实用程序将此上下文映射到正在运行的系统:~]# restorecon -R -v /opt/postgresql
- 现在,
/opt/postgresql/
位置已使用 PostgreSQL 的正确上下文标记,postgresql
服务将成功启动:~]# systemctl start postgresql.service
- 确认
/opt/postgresql/
的上下文正确:~]$ ls -lZ /opt drwxr-xr-x. root root system_u:object_r:postgresql_db_t:s0 postgresql
- 使用 ps 命令检查
postgresql
进程显示新位置:~]# ps aux | grep -i postmaster postgres 21564 0.3 0.3 42308 4032 ? S 10:13 0:00 /usr/bin/postmaster -p 5432 -D /opt/postgresql/data/
- 该位置已更改并标记,
postgresql
已成功启动。此时,应测试所有正在运行的服务,以确认正常运行。