How to Install PostgreSQL on Ubuntu 24.04

Aybars Altınyay
Aybars Altınyay
Platform Engineer & Technical Writer
BeginnerUpdated Nov 17, 202621 min read~30 minutes total
PostgreSQLUbuntu 24.04PostgreSQL 18DatabaseLinuxSQL
Last reviewed:
Tutorial
How to Install PostgreSQL on Ubuntu 24.04
rafftechnologies.com/learn
On this page

Prerequisites

  • Ubuntu 24.04 LTS on a Raff Linux VM
  • SSH access with a sudo-capable user
  • A recovery or console path before firewall changes
  • A unique application database password stored outside source code
  • A backup plan before modifying an existing PostgreSQL installation

Run PostgreSQL 18 on your own Ubuntu 24.04 server.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month

  1. 1Pick a Linux imageUbuntu, Debian and more, with your SSH key added.
  2. 2Choose a sizeFrom $4.99 a month. Resize when your app grows.
  3. 3Connect over SSHYour server is up in about 55 seconds.

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

In this tutorial, you will install PostgreSQL 18 on a Raff Ubuntu 24.04 VM, create an application database and role, verify SCRAM authentication, keep port 5432 private, and prove a logical backup can be restored.

Ubuntu 24.04's standard postgresql package tracks PostgreSQL 16, while the official PostgreSQL Apt repository (PGDG) provides newer supported major versions. This procedure uses PGDG to install PostgreSQL 18. PostgreSQL 18.6 is the current maintenance release as of September 17, 2026, while Ubuntu 24.04 currently maintains PostgreSQL 16.15 on its distro package path.

Choose a Raff Linux VM if you need operating-system access and want to manage PostgreSQL installation, patching, monitoring, and recovery yourself. If you prefer a managed database, compare Raff Managed PostgreSQL before starting. The managed service has its own supported PostgreSQL versions, so this PostgreSQL 18 procedure is for the self-hosted VM path only.

Prerequisites:

  • A Raff Ubuntu 24.04 Linux VM running a self-managed PostgreSQL instance
  • SSH access with a sudo-capable user
  • A recovery or console path before firewall changes
  • A unique application database password stored outside source code
  • A backup plan before modifying an existing PostgreSQL installation

The original workflow was tested on a Raff VM with 2 vCPU and 4 GB RAM. This refresh re-verifies PostgreSQL 18.6 and Ubuntu 24.04 package guidance against current upstream documentation without claiming a new full machine retest.

Ubuntu repository vs PGDG: sudo apt install postgresql is valid and installs Ubuntu's maintained PostgreSQL 16 line on Ubuntu 24.04. Use PGDG when PostgreSQL 18 is the target.

Step 1 — Update Ubuntu and verify the release

Update package metadata and installed packages:

Bash
sudo apt update sudo apt upgrade -y

Install the packages used by the PGDG setup and later checks:

Bash
sudo apt install -y curl ca-certificates postgresql-common

Verify the Ubuntu release:

Bash
. /etc/os-release printf '%s\n%s\n' "$PRETTY_NAME" "$VERSION_CODENAME"

Expected values include:

Text
Ubuntu 24.04 LTS noble

Check whether a reboot is required:

Bash
if [ -f /var/run/reboot-required ]; then echo "Reboot required before continuing" else echo "No reboot required" fi

Verify: the host reports Ubuntu 24.04 with codename noble, package updates complete successfully, and any required reboot is handled before PostgreSQL installation.

Step 2 — Add the official PostgreSQL Apt repository

Add the PGDG repository using the helper shipped by postgresql-common:

Bash
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh

Verify the configured repository:

Bash
grep -R "apt.postgresql.org" \ /etc/apt/sources.list.d/pgdg.list \ /etc/apt/sources.list.d/pgdg.sources 2>/dev/null

The output includes apt.postgresql.org and noble-pgdg.

Confirm PostgreSQL 18 is available:

Bash
apt-cache policy postgresql-18 | sed -n '1,14p'

A non-empty Candidate from the PGDG repository confirms the package is available.

Verify: the configured source references apt.postgresql.org, targets noble-pgdg, and exposes a PostgreSQL 18 candidate package.

Step 3 — Install PostgreSQL 18

Install the PostgreSQL 18 server and matching client:

Bash
sudo apt install -y postgresql-18 postgresql-client-18

Verify the client version:

Bash
psql --version

Expected format:

Text
psql (PostgreSQL) 18.x

List the PostgreSQL clusters managed by Ubuntu tooling:

Bash
pg_lsclusters

A normal new installation includes an 18/main cluster, commonly on port 5432:

Text
Ver Cluster Port Status Owner Data directory 18 main 5432 online postgres /var/lib/postgresql/18/main

Query the running server version:

Bash
sudo -u postgres psql -tAc "SHOW server_version;"

PostgreSQL 18.6 is the current PostgreSQL 18 maintenance release as of September 17, 2026. Version 18.5 was not released because a regression was found before shipment.

If another PostgreSQL major version already exists, inspect pg_lsclusters before changing ports, packages, or data directories.

Verify: psql reports PostgreSQL 18.x, pg_lsclusters shows the intended cluster online, and SHOW server_version reports PostgreSQL 18.6 or a later supported 18.x maintenance release.

Step 4 — Verify service health and local readiness

Check the cluster-specific systemd unit:

Bash
systemctl is-active postgresql@18-main systemctl is-enabled postgresql@18-main

Expected output:

Text
active enabled

Check the local TCP endpoint:

Bash
sudo -u postgres pg_isready -h 127.0.0.1 -p 5432

Expected output:

Text
127.0.0.1:5432 - accepting connections

Read the data directory and active configuration file from PostgreSQL itself:

Bash
sudo -u postgres psql -tAc "SHOW data_directory;" sudo -u postgres psql -tAc "SHOW config_file;"

Verify: the 18/main service is active and enabled, pg_isready reports that PostgreSQL is accepting connections, and the server returns the expected 18/main paths.

Step 5 — Create an application role and database

Open psql as the local PostgreSQL administrator:

Bash
sudo -u postgres psql

Create a dedicated login role and application database:

Sql
CREATE ROLE raffappuser WITH LOGIN; CREATE DATABASE raffapp OWNER raffappuser; \password raffappuser

Enter a unique application password twice when prompted, then exit:

Sql
\q

Verify the role:

Bash
sudo -u postgres psql -tAc \ "SELECT rolname, rolcanlogin FROM pg_roles WHERE rolname = 'raffappuser';"

Expected output:

Text
raffappuser|t

Verify database ownership:

Bash
sudo -u postgres psql -tAc \ "SELECT datname || '|' || pg_get_userbyid(datdba) FROM pg_database WHERE datname = 'raffapp';"

Expected output:

Text
raffapp|raffappuser

Do not use the postgres superuser from application code.

Verify: raffappuser can log in and owns the raffapp database.

Step 6 — Verify SCRAM authentication

Find the active host-based authentication file:

Bash
HBA_FILE="$(sudo -u postgres psql -tAc 'SHOW hba_file;' | xargs)" echo "$HBA_FILE"

Inspect the parsed HBA rules:

Bash
sudo -u postgres psql -P pager=off -x -c \ "SELECT line_number,type,database,user_name,address,auth_method,error FROM pg_hba_file_rules ORDER BY line_number;"

Verify the password-encryption setting:

Bash
sudo -u postgres psql -tAc "SHOW password_encryption;"

Expected output:

Text
scram-sha-256

Test the application role over TCP:

Bash
psql -h 127.0.0.1 -U raffappuser -d raffapp -W \ -c "SELECT current_user, current_database();"

Expected output includes:

Text
current_user | current_database --------------+----------------- raffappuser | raffapp

Do not change authentication to trust to work around a failed login. Inspect the matching pg_hba.conf rule and correct the underlying account or rule issue.

Verify: password_encryption is scram-sha-256, localhost TCP requires authentication, and raffappuser connects successfully to raffapp.

Step 7 — Keep PostgreSQL off the public network

Check the configured listen addresses:

Bash
sudo -u postgres psql -tAc "SHOW listen_addresses;"

For this single-VM deployment, expected output is:

Text
localhost

Inspect active listeners:

Bash
sudo ss -lntp | grep ':5432'

Expected listeners are loopback only, such as:

Text
127.0.0.1:5432 [::1]:5432

If PostgreSQL listens on 0.0.0.0, [::], or a public interface, locate the active configuration file:

Bash
CONFIG_FILE="$(sudo -u postgres psql -tAc 'SHOW config_file;' | xargs)" echo "$CONFIG_FILE"

Set:

Conf
listen_addresses = 'localhost'

Restart and verify again:

Bash
sudo systemctl restart postgresql@18-main sudo ss -lntp | grep ':5432'

Check UFW state without enabling it blindly from a remote shell:

Bash
sudo ufw status verbose

If UFW is already active, confirm there is no broad public allow rule for 5432/tcp. Add an explicit deny only when it does not conflict with an intentional private-network design:

Bash
sudo ufw deny 5432/tcp sudo ufw status numbered

For an application on another VM, use Raff VPC, bind PostgreSQL only to the required private interface, and restrict pg_hba.conf to the application's private source range.

Verify: PostgreSQL listens only on loopback for this tutorial and no firewall rule exposes TCP 5432 to the public internet.

Step 8 — Run an authenticated CRUD test

Create a temporary PGPASSFILE so automated checks do not put the application password in command history:

Bash
read -rsp "PostgreSQL password: " DB_PASSWORD echo PGPASSFILE="$(mktemp)" chmod 600 "$PGPASSFILE" printf '127.0.0.1:5432:*:raffappuser:%s\n' "$DB_PASSWORD" > "$PGPASSFILE" unset DB_PASSWORD export PGPASSFILE

Run create, insert, update, and select operations:

Bash
psql -h 127.0.0.1 -U raffappuser -d raffapp <<'SQL' CREATE TABLE tutorial_check ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL UNIQUE, status TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); INSERT INTO tutorial_check (name, status) VALUES ('raff-postgresql-test', 'created'); UPDATE tutorial_check SET status = 'verified' WHERE name = 'raff-postgresql-test'; SELECT name, status FROM tutorial_check WHERE name = 'raff-postgresql-test'; SQL

Expected result includes:

Text
name | status ----------------------+---------- raff-postgresql-test | verified

Confirm the application role owns the table:

Bash
psql -h 127.0.0.1 -U raffappuser -d raffapp -tAc \ "SELECT tableowner FROM pg_tables WHERE schemaname='public' AND tablename='tutorial_check';"

Expected output:

Text
raffappuser

Leave the test row and table in place for the restore test in the next step.

Verify: the non-superuser application role creates, reads, updates, and owns its application table over authenticated TCP.

Step 9 — Back up and restore the database

Create a protected backup directory and a custom-format logical dump:

Bash
BACKUP_DIR="$HOME/postgresql-tutorial-backup" mkdir -p "$BACKUP_DIR" chmod 700 "$BACKUP_DIR" pg_dump \ -h 127.0.0.1 \ -U raffappuser \ -d raffapp \ -F c \ -f "$BACKUP_DIR/raffapp.dump"

Confirm the dump is non-empty and readable:

Bash
test -s "$BACKUP_DIR/raffapp.dump" && echo "Backup file is non-empty" pg_restore -l "$BACKUP_DIR/raffapp.dump" | head -n 20

Create an isolated restore database:

Bash
sudo -u postgres createdb -O raffappuser raffapp_restore_test

Restore the backup without replaying original ownership or privilege metadata:

Bash
pg_restore \ -h 127.0.0.1 \ -U raffappuser \ -d raffapp_restore_test \ --no-owner \ --no-privileges \ "$BACKUP_DIR/raffapp.dump"

Query the restored row:

Bash
psql -h 127.0.0.1 -U raffappuser -d raffapp_restore_test -c \ "SELECT name, status FROM tutorial_check WHERE name='raff-postgresql-test';"

Expected result:

Text
raff-postgresql-test | verified

Remove only the disposable restore database and tutorial table:

Bash
sudo -u postgres dropdb --if-exists raffapp_restore_test psql -h 127.0.0.1 -U raffappuser -d raffapp -c \ "DROP TABLE tutorial_check;"

Remove the temporary password file:

Bash
rm -f "$PGPASSFILE" unset PGPASSFILE

A single pg_dump is not a complete production recovery strategy. For production recovery design, use PostgreSQL Replication vs Backups vs Snapshots.

Verify: the backup is non-empty, pg_restore can read it, the isolated restore succeeds, and the restored row contains verified.

Step 10 — Verify the complete PostgreSQL installation

Run the final server checks:

Bash
systemctl is-active postgresql@18-main pg_lsclusters sudo -u postgres pg_isready -h 127.0.0.1 -p 5432 sudo -u postgres psql -tAc "SHOW server_version;" sudo -u postgres psql -tAc "SHOW listen_addresses;" sudo ss -lntp | grep ':5432'

Verify the application role and database still exist:

Bash
sudo -u postgres psql -tAc \ "SELECT rolname FROM pg_roles WHERE rolname='raffappuser';" sudo -u postgres psql -tAc \ "SELECT datname FROM pg_database WHERE datname='raffapp';"

The installation is complete when all of these conditions are true:

  • postgresql@18-main is active and enabled
  • SHOW server_version reports a supported PostgreSQL 18 maintenance release
  • pg_isready accepts local connections on port 5432
  • raffappuser authenticates to raffapp
  • the authenticated CRUD test succeeded
  • the logical backup restored successfully into an isolated database
  • PostgreSQL listens only on loopback for this deployment
  • no public firewall rule exposes port 5432

Verify: all commands above complete successfully and the final state matches every item in the checklist.

Cleanup (optional)

Use this cleanup only if raffapp and raffappuser were created solely for this tutorial.

Terminate remaining sessions, drop the database, and then drop the role:

Bash
sudo -u postgres psql <<'SQL' SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'raffapp' AND pid <> pg_backend_pid(); DROP DATABASE IF EXISTS raffapp; DROP ROLE IF EXISTS raffappuser; SQL

Verify removal:

Bash
sudo -u postgres psql -tAc \ "SELECT datname FROM pg_database WHERE datname='raffapp';" sudo -u postgres psql -tAc \ "SELECT rolname FROM pg_roles WHERE rolname='raffappuser';"

Both queries return no rows.

Do not purge PostgreSQL packages or delete /var/lib/postgresql unless you have identified every cluster on the VM and confirmed that none contains data you need.

Troubleshooting

postgresql-18 has no installation candidate

Check the Ubuntu codename and PGDG repository:

Bash
. /etc/os-release echo "$VERSION_CODENAME" grep -R "apt.postgresql.org" /etc/apt/sources.list.d 2>/dev/null sudo apt update apt-cache policy postgresql-18

If PGDG is missing, rerun the official repository helper:

Bash
sudo apt install -y postgresql-common sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh

sudo apt install postgresql installed PostgreSQL 16

That is the expected Ubuntu 24.04 distro path. Ubuntu's postgresql metapackage tracks PostgreSQL 16. Use PGDG and install postgresql-18 when PostgreSQL 18 is required.

Check existing clusters before removing anything:

Bash
pg_lsclusters

The 18/main cluster is offline

Inspect cluster state and logs:

Bash
pg_lsclusters sudo systemctl status postgresql@18-main --no-pager sudo journalctl -u postgresql@18-main --no-pager -n 100

Check for a port conflict:

Bash
sudo ss -lntp | grep ':5432'

After correcting the reported issue, restart the service:

Bash
sudo systemctl restart postgresql@18-main systemctl is-active postgresql@18-main

Password authentication fails

Confirm the role can log in:

Bash
sudo -u postgres psql -tAc \ "SELECT rolname, rolcanlogin FROM pg_roles WHERE rolname='raffappuser';"

Inspect parsed HBA rules:

Bash
sudo -u postgres psql -P pager=off -x -c \ "SELECT line_number,type,database,user_name,address,auth_method,error FROM pg_hba_file_rules ORDER BY line_number;"

Reset the role password without putting it in shell history:

Bash
sudo -u postgres psql

Then run:

Sql
ALTER ROLE raffappuser WITH LOGIN; \password raffappuser \q

Retest:

Bash
psql -h 127.0.0.1 -U raffappuser -d raffapp -W \ -c "SELECT current_user, current_database();"

PostgreSQL listens on a public interface

Find the active configuration file:

Bash
CONFIG_FILE="$(sudo -u postgres psql -tAc 'SHOW config_file;' | xargs)" echo "$CONFIG_FILE"

For this tutorial, set:

Conf
listen_addresses = 'localhost'

Restart and verify:

Bash
sudo systemctl restart postgresql@18-main sudo ss -lntp | grep ':5432'

pg_restore fails during the restore test

Confirm the dump is a valid custom-format archive:

Bash
file "$BACKUP_DIR/raffapp.dump" pg_restore -l "$BACKUP_DIR/raffapp.dump" | head

Confirm the disposable restore database exists and is owned by raffappuser:

Bash
sudo -u postgres psql -tAc \ "SELECT datname || '|' || pg_get_userbyid(datdba) FROM pg_database WHERE datname='raffapp_restore_test';"

Drop and recreate only the disposable restore database before retrying if a previous failed restore left objects behind.

FAQ

Which PostgreSQL version is included with Ubuntu 24.04?

Ubuntu 24.04's standard postgresql package tracks PostgreSQL 16. The current Ubuntu 24.04 PostgreSQL 16 security package is 16.15 as of September 17, 2026.

What is the current PostgreSQL 18 version?

PostgreSQL 18.6 is the current stable maintenance release as of September 17, 2026. PostgreSQL 19 remains a development release and is not the production target used here.

Should PostgreSQL port 5432 be open to the internet?

No. Keep PostgreSQL on localhost when the application shares the VM. For separate servers, use private networking and allow only required private source ranges.

How should I create a PostgreSQL application user?

Create a dedicated login role, make it owner of the intended application database when that model fits, and set its password with \password so the secret is not stored in shell history.

Is pg_dump enough for production backups?

Not by itself. Production recovery also needs retention, off-server copies, monitoring, restore testing, and, when required, WAL archiving and point-in-time recovery.

Should I self-host PostgreSQL or use managed PostgreSQL?

Self-host when you need host-level control and can own patching, backups, monitoring, upgrades, and incidents. Use managed PostgreSQL when reducing operational ownership matters more.

Conclusion

You now have PostgreSQL 18 running on a Raff Ubuntu 24.04 VM with a dedicated application role, SCRAM authentication, private-by-default networking, verified CRUD operations, and a restore-tested logical backup.

For production planning, continue with PostgreSQL for SaaS Apps and Back Up PostgreSQL to Raff Object Storage with Restic. The replication-versus-backup guide and Raff Managed PostgreSQL option are linked alongside the relevant setup decisions above.

Deploy a Raff Ubuntu VM for a self-hosted PostgreSQL 18 setup. Choose compute and storage based on your workload, and manage database maintenance and backups yourself.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month · 14-day money-back guarantee

Deploy Your Server
Was this article helpful?
Aybars Altınyay
Aybars Altınyay
Platform Engineer & Technical Writer

Aybars is a Platform Engineer & Technical Writer at Raff Technologies. He works on Linux VM templates, self-hosted application workflows, and security-focused deployment validation, turning tested infrastructure procedures into clear, practical tutorials for developers and teams.

Run PostgreSQL 18 on your own Ubuntu 24.04 server.

Tested on 2 vCPU and 4 GB RAM: $17.99 a month

Ubuntu, Debian and other Linux distributions with full root and SSH access, up and running in about 55 seconds.

14-day money-back guarantee

Frequently asked questions

Which PostgreSQL version is included with Ubuntu 24.04?
Ubuntu 24.04's standard postgresql package tracks PostgreSQL 16. The current Ubuntu 24.04 PostgreSQL 16 security package is 16.15 as of September 17, 2026.
What is the current PostgreSQL 18 version?
PostgreSQL 18.6 is the current stable maintenance release as of September 17, 2026. PostgreSQL 19 remains a development release and is not the production target used here.
Should PostgreSQL port 5432 be open to the internet?
No. Keep PostgreSQL on localhost when the application shares the VM. For separate servers, use private networking and allow only required private source ranges.
How should I create a PostgreSQL application user?
Create a dedicated login role, make it owner of the intended application database when that model fits, and set its password with the psql password command so the secret is not stored in shell history.
Is pg_dump enough for production backups?
Not by itself. Production recovery also needs retention, off-server copies, monitoring, restore testing, and, when required, WAL archiving and point-in-time recovery.
Should I self-host PostgreSQL or use managed PostgreSQL?
Self-host when you need host-level control and can own patching, backups, monitoring, upgrades, and incidents. Use managed PostgreSQL when reducing operational ownership matters more.