How to install PostgreSQL on Linux
Topic: Databases core
Summary
Install PostgreSQL on Debian, Ubuntu, or RHEL using the official or distro package repository. Configure the data directory, init the cluster, and start the server so you can create databases and users. Use this when setting up a new database server or when you need a specific PostgreSQL version.
Intent: How-to
Quick answer
- Debian/Ubuntu: add apt.postgresql.org repo or use apt install postgresql-16; RHEL: dnf install postgresql-server. Run postgresql-setup --initdb (RHEL) or pg_createcluster (Debian) if needed.
- Start and enable: systemctl start postgresql; systemctl enable postgresql. Connect as postgres user with psql or sudo -u postgres psql. Data directory is typically /var/lib/pgsql/data or /var/lib/postgresql/VERSION/main.
- Create a superuser and database; configure listen_addresses and pg_hba.conf for remote access if required. Secure the postgres OS account and restrict network access.
Steps
-
Add repository and install
Debian/Ubuntu: follow postgresql.org apt instructions for your distro; install postgresql-16 or desired version. RHEL: dnf install postgresql-server postgresql-contrib.
-
Initialize and start
RHEL: postgresql-setup --initdb. Debian: cluster may auto-init. systemctl start postgresql; systemctl enable postgresql; systemctl status postgresql.
-
Connect and create database
sudo -u postgres psql. CREATE USER myuser WITH PASSWORD 'x'; CREATE DATABASE mydb OWNER myuser; \q. Test: psql -U myuser -d mydb -h localhost.
-
Configure for remote (optional)
Set listen_addresses in postgresql.conf; add host entries in pg_hba.conf for allowed clients. Restart PostgreSQL. Restrict to required IPs; use SSL in production.
Summary
Install PostgreSQL from the official or distro repo, initialize the cluster, start and enable the service, then create a database and user. Use this when standing up a new DB server or when you need a specific PostgreSQL version.
Prerequisites
- Root or sudo on a Linux host (Debian, Ubuntu, or RHEL).
Steps
Step 1: Add repository and install
Add the PostgreSQL APT or DNF repository for your distro; install the desired major version (e.g. postgresql-16).
Step 2: Initialize and start
Initialize the data directory if required (postgresql-setup or pg_createcluster); start and enable the service with systemctl.
Step 3: Connect and create database
Connect as the postgres user; create a role and database; verify local connection with psql.
Step 4: Configure for remote (optional)
Set listen_addresses and pg_hba.conf for remote access; restart; use SSL and restrict IPs in production.
Verification
- systemctl status postgresql is active; sudo -u postgres psql connects; you can create a database and user and connect as that user.
Troubleshooting
Service won’t start — Check logs (journalctl -u postgresql); fix data directory permissions or corrupt cluster. Connection refused — listen_addresses and pg_hba.conf must allow the client; restart after changes.