Arch Linux下PostgreSQL初始化数据库集群遇目录及权限问题求助
Hey there, let's work through this PostgreSQL init headache on Arch Linux step by step—you're close to getting it sorted!
First: Address the "non-empty default directory" error
The error about /var/lib/postgres/data being non-empty is common, and it's usually safe to clean up that directory if you haven't already set up a cluster there. First, let's check what's actually in it to be sure:
sudo ls -la /var/lib/postgres/data
If you only see stray logs, temporary files, or leftover setup artifacts, back them up somewhere safe then empty the directory with:
sudo rm -rf /var/lib/postgres/data/*
Once it's empty, you can run your original initdb command as the postgres user, and it should work without issues.
If you still don't want to touch the default directory, let's fix the custom directory permission problem you ran into.
Fixing Custom Directory Permissions
Your permission error is almost certainly caused by parent directory restrictions—by default, /home/user is set to 700 permissions, which means the postgres user can't even access that directory, no matter what permissions you set on the subfolder. Here's how to fix it:
Adjust parent directory access
If you're set on using/home/user/postgres/data, first give the postgres user permission to traverse the parent folders:sudo chmod o+x /home/user sudo chmod o+x /home/user/postgresThis doesn't give other users full access—it just lets them navigate into the directories (which is required to reach the data folder).
Lock down the data directory properly
Make sure the data folder is fully owned by postgres, with strict permissions (PostgreSQL requires700to keep data secure):sudo chown -R postgres:postgres /home/user/postgres/data sudo chmod 700 /home/user/postgres/dataRun initdb as the postgres user
Switch back to the postgres user and run initdb again—this time it should work:sudo -iu postgres initdb -D /home/user/postgres/dataSet up auto-start for your custom cluster
To make PostgreSQL start on boot with your custom directory, copy the default systemd service file and tweak it:sudo cp /usr/lib/systemd/system/postgresql.service /etc/systemd/system/postgresql-custom.service sudo nano /etc/systemd/system/postgresql-custom.serviceFind the line that says
Environment=PGDATA=/var/lib/postgres/dataand replace it with your custom path:Environment=PGDATA=/home/user/postgres/dataThen reload systemd and enable the new service:
sudo systemctl daemon-reload sudo systemctl enable --now postgresql-custom.service
Pro Tip: Use the Official Arch Setup Script
If you want to skip all the manual steps, Arch Linux provides a handy script that handles initialization automatically—just run:
sudo postgresql-setup --initdb
It'll check the default directory, prompt you to clean it if needed, and set up everything correctly in one go. Super convenient!
内容的提问来源于stack exchange,提问作者U. Watt

