Wednesday, December 4, 2013

SELinux & PostgreSQL PGDATA *not* in /var/lib/pgsql/data

I've been playing around with PostgreSQL for years but never used in professionally.  I use MySQL for pay but more on that later.  Both have default locations for the actual files that contain the data, etc. and these locations are already configured in SELinux so the RDBMS can start without issues.  But what about putting the data in a location other than the default?  I tried this and the database manager would not start because of permissions violations.  I did a lot of research and it took a long time but I could never find everything I needed in one place.  For a while I just turned SELinux off so I didn't have to worry about it but in this world of security consciousness that is not a good answer.

Please remember that all the commands must be run as root.  I use sudo either on a per-command basis or using the -i option which does the same thing as su -.

First, add PGDATA & PGLOG to /etc/sysconfig/pgsql/postgresql using your favorite editor.  I use vi because I've been using it for over 20 years...  (Yes, I've been doing this for a while.)  I use the following for my database location with /db being a separate filesystem:

Now add the contexts to SELinux. The documentation says to use semanage to update the file /etc/selinux/targeted/contexts/files/file_contexts.local but does not say how to do it, so I manually edit the file. Add lines to the file with the new paths like these (I'm using the example above):
    /db/pgsql(/.*)?                  system_u:object_r:postgresql_db_t:s0
    /db/pgsql/data(/.*)?             system_u:object_r:postgresql_db_t:s0
    /db/pgsql/logfile(/.*)?          system_u:object_r:postgresql_log_t:s0
    /db/pgsql/pgstartup\.log.*       system_u:object_r:postgresql_log_t:s0
Before executing service, make sure the paths exist and are owned by postgres:
    ls -ld /db/pgsql /db/pgsql/data
it should look like
    drwxr-xr-x.  3  postgres postgres  4096 Nov  6  11:29  /db/pgsql
    drwx------. 12  postgres postgres  4096 Nov  6  11:30  /db/pgsql/data
Now initialize the database
    service postgresql initdb
if it doesn't show
    Initializing database:                                  [OK]
The something has gone wrong. If it hasn't, start the Postgres service:
    service postgresql start
which should show
    Starting postgresql service:                            [OK]
To make PostgreSQL start up on boot, execute the following command:
    chconfig postgresql on
The default runlevels for PostgreSQL are 2, 3, 4, and 5 which are the multi-user levels.

Some of the commands may behave differently on other Linux systems. I use CentOS and Fedora and they work reasonably well there.

No comments:

Post a Comment