How to Install PostgreSQL on Linux: A Step-by-Step Guide

PostgreSQL is a powerful open-source relational database management system (RDBMS) used by developers and enterprises worldwide. If you’re working on a Linux-based environment, setting up PostgreSQL is essential for handling complex queries and large-scale data. In this guide, we’ll walk you through the process of installing PostgreSQL on Linux step by step.


Step 1: Update Your System

Before installing PostgreSQL, it’s best to update your package list to ensure you have the latest software versions. Open your terminal and run:

bashCopyEditsudo apt update && sudo apt upgrade -y  # For Debian-based distros (Ubuntu, Debian)
sudo yum update -y  # For RHEL-based distros (CentOS, Fedora)

Step 2: Install PostgreSQL

For Ubuntu/Debian-based Distributions

To install PostgreSQL, use the following command:

bashCopyEditsudo apt install postgresql postgresql-contrib -y

For CentOS/Fedora (RHEL-based Distributions)

Use this command to install PostgreSQL:

bashCopyEditsudo yum install -y postgresql-server postgresql-contrib

Once installed, initialize the database:

bashCopyEditsudo postgresql-setup initdb

Then, enable and start the PostgreSQL service:

bashCopyEditsudo systemctl enable postgresql
sudo systemctl start postgresql

Step 3: Verify PostgreSQL Installation

After installation, check if PostgreSQL is running:

bashCopyEditsudo systemctl status postgresql

If it's active, PostgreSQL has been successfully installed.


Step 4: Access PostgreSQL Database

PostgreSQL creates a default user named postgres. Switch to this user and open the PostgreSQL interactive shell:

bashCopyEditsudo -i -u postgres
psql

To exit the PostgreSQL shell, type:

sqlCopyEdit\q

Step 5: Enable Remote Access (Optional)

If you want to allow remote access to your PostgreSQL server, follow these steps:

Edit PostgreSQL Configuration File

Open the postgresql.conf file:

bashCopyEditsudo nano /etc/postgresql/15/main/postgresql.conf  # Ubuntu/Debian
sudo nano /var/lib/pgsql/data/postgresql.conf  # CentOS/Fedora

Find the line:

plaintextCopyEditlisten_addresses = 'localhost'

Change it to:

plaintextCopyEditlisten_addresses = '*'

Modify pg_hba.conf File

Edit the pg_hba.conf file:

bashCopyEditsudo nano /etc/postgresql/15/main/pg_hba.conf  # Ubuntu/Debian
sudo nano /var/lib/pgsql/data/pg_hba.conf  # CentOS/Fedora

Add the following line at the end:

plaintextCopyEdithost all all 0.0.0.0/0 md5

Save the file and restart PostgreSQL:

bashCopyEditsudo systemctl restart postgresql

Final Thoughts: Need Help Installing PostgreSQL?

Setting up PostgreSQL on Linux can be tricky, especially if you need custom configurations or remote access. If this guide feels overwhelming, I can help you with installation, optimization, and database management. Contact me today for expert PostgreSQL setup services! 🚀