متقدم
البحث فيأدلة التثبيت
طريقة البحث
  • الصق رسالة الخطأ بين علامتي تنصيص، مثل "permission denied"، لتجد جدول الحل.
  • اختر مجالًا وجزءًا من الدليل (التثبيت، أول الإعدادات، الاستخدام اليومي، الأمان، الحلول) لتصل مباشرة إلى الخطوة الصحيحة.
  • "كلمتان" تجد العبارة بالضبط.
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث
جرّب:

الدليل 9PostgreSQL · Data

Install and set up PostgreSQL

PostgreSQL is the most used open-source database for new apps: reliable, fast and full of features. As a DevOps or IT engineer you install it, create the users and databases for the apps, open it safely to the app servers, tune the memory and — most important — make and test backups. This guide does all of that on RHEL and Ubuntu.

  • 11 الدروس
  • 9 الأوامر

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

$ مستخدم عادي# بصلاحية root (أو مع sudo)

9.1

Know it before you install

One PostgreSQL server (also called a cluster) holds many databases. Users are roles. Who may connect from where, and how, is written in pg_hba.conf; how the server works is in postgresql.conf.

ItemRHEL / Rocky / Alma / FedoraUbuntu / Debian
Packagespostgresql-server, postgresqlpostgresql
Servicepostgresql.servicepostgresql.service (and postgresql@16-main)
Data folder/var/lib/pgsql/data//var/lib/postgresql/16/main/
Config filesin the data folder/etc/postgresql/16/main/
Logs/var/lib/pgsql/data/log//var/log/postgresql/
Port5432/tcp5432/tcp
Admin userLinux user postgres + role postgresthe same

الأوامر في هذا الدرس

9.2

Install on RHEL, Rocky, Alma and Fedora

RHEL has more than one version as module streams (RHEL 8/9). Choose one, install, create the data folder, and start:

dnf module list postgresql
dnf -y module enable postgresql:16
dnf -y install postgresql-server postgresql
postgresql-setup --initdb
 * Initializing database in '/var/lib/pgsql/data'
 * Initialized, logs are in /var/lib/pgsql/initdb_postgresql.log
systemctl enable --now postgresql

On RHEL 10 there are no module streams; dnf install postgresql-server gives version 16. Work tip: The newest version (17, 18) comes from the official PGDG repository (download.postgresql.org); there the service is postgresql-17.

9.3

Install on Ubuntu and Debian

On Ubuntu the package creates the cluster and starts it:

apt-get update
apt-get install -y postgresql
pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
16  main    5432 online postgres /var/lib/postgresql/16/main /var/log/postgresql/postgresql-16-main.log

9.4

First steps: an app user and database

Log in as the admin with peer authentication (the Linux user postgres, no password):

sudo -u postgres psql

Create a role for the app and its database. Each app gets its own role and database — never use postgres in apps:

psql
CREATE ROLE shop LOGIN PASSWORD 'change-me-long-random';
CREATE DATABASE shop OWNER shop;
\l
\du
\q

Test the login over TCP (this uses a password, not peer):

psql -h 127.0.0.1 -U shop -d shop -c 'select version();'

الأوامر في هذا الدرس

9.5

First configuration: network access and memory

By default PostgreSQL listens only on localhost. To allow the app servers, change two files.

In postgresql.conf (RHEL: /var/lib/pgsql/data/, Ubuntu: /etc/postgresql/16/main/):

postgresql.conf
listen_addresses = 'localhost,10.0.1.21'
max_connections = 200
shared_buffers = 2GB
effective_cache_size = 6GB
work_mem = 16MB
maintenance_work_mem = 512MB
password_encryption = scram-sha-256
log_min_duration_statement = 500ms
log_line_prefix = '%m [%p] %u@%d '
SettingWhy
listen_addressesThe IP addresses to listen on. Only the private IP, not * on a public server.
shared_buffersAbout 25 % of RAM (here an 8 GB server).
effective_cache_sizeAbout 75 % of RAM — helps the query planner.
password_encryption = scram-sha-256The safe password hash (default since version 14).
log_min_duration_statementLog slow queries (over 500 ms) to find problems.

In pg_hba.conf allow only the app subnet, only to its database, only with a password:

pg_hba.conf
# TYPE  DATABASE  USER  ADDRESS        METHOD
local   all       postgres             peer
host    shop      shop  10.0.1.0/24    scram-sha-256

Restart (for listen_addresses and shared_buffers) and open the firewall only for the app subnet:

systemctl restart postgresql
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.1.0/24" service name="postgresql" accept'
firewall-cmd --reload
ufw allow from 10.0.1.0/24 to any port 5432 proto tcp

تذكّر

Changes in pg_hba.conf need only a reload: systemctl reload postgresql or SELECT pg_reload_conf();. Changes to listen_addresses and shared_buffers need a restart.

9.6

Backups: the most important job

A logical backup of one database, in the compressed custom format:

sudo -u postgres pg_dump -Fc -d shop -f /backup/shop-$(date +%F).dump
sudo -u postgres pg_dumpall --globals-only > /backup/globals-$(date +%F).sql
sudo -u postgres createdb shop_test
sudo -u postgres pg_restore -d shop_test /backup/shop-2026-11-16.dump

Run the backup every night with a timer or cron, copy it to another place (object storage), and test the restore regularly — a backup you never restored is only a hope. For big databases and point-in-time recovery use pgBackRest or barman.

9.7

Daily use: the commands and the real uses

In psql:

psql
\c shop                 -- connect to a database
\dt                     -- list tables
\d+ orders              -- one table, with sizes
\x                      -- wide rows as a list
SELECT pid, usename, state, now() - query_start AS time, query
  FROM pg_stat_activity WHERE state <> 'idle';
SELECT pg_size_pretty(pg_database_size('shop'));
SELECT pg_cancel_backend(12345);

Real uses at work:

  • Give each app its own role and database; rotate the passwords.
  • Find slow queries (pg_stat_activity, slow query log, EXPLAIN ANALYZE).
  • Nightly backups and restore tests; upgrades between major versions.
  • In containers for labs: docker run -d -e POSTGRES_PASSWORD_FILE=… postgres:16.

9.8

Make it safe

Security checklist:

  • Never open 5432 to the internet. Listen on the private IP; firewall only for the app servers.
  • scram-sha-256 everywhere in pg_hba.conf; never trust on TCP lines.
  • One role per app with only the rights it needs; no apps as postgres.
  • TLS for connections over the network (ssl = on with a certificate).
  • Encrypted backups in another place, with restore tests.
  • Keep minor versions up to date (security fixes).

9.9

Update and remove

Minor updates (16.4 → 16.6) are normal package updates plus a restart:

dnf -y upgrade postgresql-server postgresql
apt-get install --only-upgrade -y postgresql
systemctl restart postgresql

Major upgrades (16 → 17) change the data format: use pg_upgrade (RHEL: postgresql-upgrade; Ubuntu: pg_upgradecluster 16 main), or dump and restore. Always make a backup first.

9.10

Fix common problems

ProblemCauseFix
Peer authentication failed for user "shop"You connected over the socket; the local line says peer.Use -h 127.0.0.1, or change the local line to scram-sha-256.
no pg_hba.conf entry for host "10.0.1.15"No line allows this IP, user or database.Add a host line, then reload.
Connection refused from another serverListens only on localhost, or the firewall.listen_addresses, restart; open 5432 for that subnet.
FATAL: role "x" does not existThe role was not created.CREATE ROLE x LOGIN PASSWORD '…';
FATAL: sorry, too many clients alreadymax_connections is reached.Close idle connections; use a pool (PgBouncer).
The disk fills upWAL, logs or table bloat.du -sh on the data folder; check replication slots and archiving; let autovacuum work.
postgresql-setup: … Data directory is not emptyinitdb was already done.Nothing to do — just start the service.

الأوامر في هذا الدرس

9.11

Next steps

1Which two files do you change so an app server can connect?

postgresql.conf (listen_addresses) and pg_hba.conf (a host line with scram-sha-256).

2When is a backup really a backup?

When you have restored it once and it worked.

الأوامر في هذا الدرس

كل الأوامر في هذا الفصل