Website Vidya
Linux & ServersStep-by-Step Guide

How to Install and Configure PostgreSQL on Ubuntu 24.04

Learn how to install postgresql on ubuntu 24.04 with roles, databases, remote access, pg_hba.conf security, and systemd service management.

RR
Rajesh RayLead Systems Educator
Published:
5 min read
PDF Cheat Sheet
How to Install and Configure PostgreSQL on Ubuntu 24.04
AI Executive SummaryWebsiteVidya AI

5 min read

Learn how to install postgresql on ubuntu 24.04 with roles, databases, remote access, pg_hba.conf security, and systemd service management.

Key Highlights
  • Prerequisites and Supported Releases
  • Step 1: Installing PostgreSQL and Contrib Packages
  • Step 2: Understanding PostgreSQL Roles and Peer Authentication
Grounded in full engineering runbookWebsiteVidya AI Engine

PostgreSQL is one of the world's most advanced open-source object-relational database management systems.

Renowned for its robust transactional reliability, ACID compliance, extensive SQL feature support, and extensible data types (including JSONB and vector embeddings), PostgreSQL powers countless modern production applications.

Ubuntu 24.04 LTS (Noble Numbat) packages PostgreSQL 16 natively in its main software repositories, providing a modern and rock-solid database platform.

Properly administering PostgreSQL requires understanding its role-based security model, peer authentication mechanism, and connection configuration files.

Advertisement

In this guide, we walk through how to install postgresql on ubuntu 24.04, create users and databases, configure remote access, and harden database security.

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat) & Ubuntu 22.04 LTS. The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Before proceeding, ensure you have the following requirements satisfied:

Advertisement
  • A server running Ubuntu 24.04 LTS or Ubuntu 22.04 LTS.
  • A non-root user account with sudo administrative privileges.
  • At least 1 GB of RAM (2 GB or more recommended for production databases).
  • Access to a bash terminal shell.

Step 1: Installing PostgreSQL and Contrib Packages

Ubuntu 24.04 LTS includes PostgreSQL 16 directly in the official main repository.

Along with the core database server, install postgresql-contrib, which provides helpful additional extensions, utility functions, and cryptographic modules:

# Update package repository lists:
sudo apt update

# Install PostgreSQL 16 and complementary modules:
sudo apt install -y postgresql postgresql-contrib

# Expected package output:
Setting up postgresql-16 (16.4-0ubuntu0.24.04.1) ...
Creating new PostgreSQL cluster 16/main ...
/usr/lib/postgresql/16/bin/initdb -D /var/lib/postgresql/16/main ...
Verifying cluster 16/main status ... online

Verifying the PostgreSQL Service Status

PostgreSQL starts automatically upon installation and enables itself to run at system boot.

Verify the daemon status using systemctl:

Advertisement
sudo systemctl status postgresql

# Output:
● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: enabled)
     Active: active (exited) since Thu 2026-10-22 11:20:14 UTC; 20s ago
   Main PID: 5612 (code=exited, status=0/SUCCESS)

Step 2: Understanding PostgreSQL Roles and Peer Authentication

By default, PostgreSQL employs a concept called roles to handle authentication and authorization.

On installation, PostgreSQL creates a Linux system user named postgres associated with the default postgres superuser database role.

Under the default peer authentication configuration, if your current Linux operating system username matches a PostgreSQL role name, you can log in without a password.

# Switch to the postgres system user and open the psql shell:
sudo -i -u postgres psql

# Welcome prompt:
psql (16.4 (Ubuntu 16.4-0ubuntu0.24.04.1))
Type "help" for help.

postgres=#

Running SQL Queries Directly with sudo -u

You can execute database queries directly from your bash shell without opening an interactive psql session:

This pattern is ideal for automation scripts and backups:

# Query PostgreSQL version directly:
sudo -u postgres psql -c "SELECT version();"

# Output:
# PostgreSQL 16.4 (Ubuntu 16.4-0ubuntu0.24.04.1) on x86_64-pc-linux-gnu

Step 3: Creating a Dedicated Database Role and Database

Production applications should never connect to PostgreSQL using the default postgres superuser account.

Instead, create a dedicated database role with an encrypted password and a dedicated database owned by that role.

Use PostgreSQL's built-in wrapper utilities from the command line:

# 1. Create a new user role with password prompt:
sudo -u postgres createuser --interactive -P appuser
# Enter password for new role: 
# Enter it again: 
# Shall the new role be a superuser? (y/n) n
# Shall the new role be allowed to create databases? (y/n) n
# Shall the new role be allowed to create more new roles? (y/n) n

# 2. Create a dedicated database owned by the new role:
sudo -u postgres createdb -O appuser production_db

Testing Local Database Connectivity with psql

Test connecting to your newly created database using the new application credentials over local TCP sockets (127.0.0.1):

psql -h 127.0.0.1 -U appuser -d production_db
# Password for user appuser: 
# psql (16.4)
# production_db=>

Step 4: Configuring Secure Remote Access in pg_hba.conf

By default, PostgreSQL listens exclusively on localhost (127.0.0.1) and rejects all external network connections.

To allow remote application servers or development teams to connect, you must modify two configuration files in /etc/postgresql/16/main/.

First, update postgresql.conf to instruct the daemon to listen on external network interfaces:

# Edit postgresql.conf to listen on all or specific interfaces:
sudo sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/" /etc/postgresql/16/main/postgresql.conf

Configuring Client Authentication in pg_hba.conf

Next, configure the client authentication policy file located at /etc/postgresql/16/main/pg_hba.conf.

Add an explicit rule granting your application server's IP address access using secure scram-sha-256 password authentication:

# Append remote access rule for application subnet (e.g. 192.168.1.0/24):
echo "host    production_db   appuser         192.168.1.0/24          scram-sha-256" | sudo tee -a /etc/postgresql/16/main/pg_hba.conf

# Restart PostgreSQL to apply changes:
sudo systemctl restart postgresql

Step 5: Configuring UFW Firewall for PostgreSQL

PostgreSQL listens on default TCP port 5432.

Never expose port 5432 openly to the entire Internet (0.0.0.0/0) without restricting source IP addresses.

Use UFW to allow connections specifically from your designated application server IP:

# Allow incoming PostgreSQL traffic only from trusted application server IP:
sudo ufw allow from 192.168.1.50 to any port 5432 proto tcp

# Reload firewall rules:
sudo ufw reload

# Verify active rule:
sudo ufw status

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

FATAL: Peer authentication failed for user username

Cause: Connecting to a local Unix domain socket using a database username that does not match the active Linux shell account.

Resolution: Specify the TCP host explicitly with -h 127.0.0.1 to trigger password authentication instead of peer authentication.

psql -h 127.0.0.1 -U appuser -d production_db

Is the server running on host X.X.X.X and accepting TCP/IP connections on port 5432?

Cause: listen_addresses is still set to 'localhost', or UFW/cloud firewall is blocking port 5432.

Resolution: Verify listen_addresses = '*' in postgresql.conf and inspect active listening sockets with ss -tulpen | grep 5432.

ss -tulpen | grep 5432

FATAL: password authentication failed for user username

Cause: Incorrect password supplied or role password has expired.

Resolution: Reset the role password from the superuser account using ALTER USER.

sudo -u postgres psql -c "ALTER USER appuser WITH PASSWORD 'new_password';"

Security Best Practices and Hardening

Always enforce modern scram-sha-256 password hashing instead of deprecated md5 in pg_hba.conf.

Never grant superuser privileges to application database roles.

Keep standard PostgreSQL port 5432 firewalled from public Internet access, routing remote traffic through private VPC networks or SSH tunnels.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Peer authentication obtains the client's operating system username from the kernel via Unix domain sockets and allows access if it matches the requested PostgreSQL database username. It is the default authentication method for local connections on Ubuntu.
To backup a database, run pg_dump -U username dbname > backup.sql. To restore the dump file into an existing database, run psql -U username -d dbname -f backup.sql.
PostgreSQL stores database tables, indexes, and write-ahead logs in /var/lib/postgresql/16/main/, while configuration files reside in /etc/postgresql/16/main/.
Log into psql and query the system view: SELECT pid, usename, client_addr, state, query FROM pg_stat_activity;.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout