How To Install Postgresql In Linux

How To Install Postgresql In Linux

Reading time1 min
#PostgreSQL#Linux#Database#PostgreSQLInstallation#LinuxDB#OpenSourceDB

Mastering PostgreSQL Installation on Linux: A Step-by-Step Guide for Precision and Performance

Installing PostgreSQL correctly on Linux sets the foundation for scalable, reliable data management essential for developers, DBAs, and system architects aiming to optimize application performance and maintain data integrity. Forget generic installation tutorials. This guide dives into the precise steps, common pitfalls, and configuration best practices to ensure your PostgreSQL server isn't just installed but primed for production-level workloads.


Why Proper PostgreSQL Installation Matters

PostgreSQL is one of the most powerful open-source relational database management systems available today. However, a sloppy or incomplete installation can lead to issues ranging from poor performance to data corruption and security vulnerabilities. By following a meticulous, step-by-step installation process, you lay the groundwork for a robust environment that scales with your application and protects your data integrity.


Step 1: Prepare Your Linux Environment

Before diving into the installation, ensure your system is updated and clean:

sudo apt update && sudo apt upgrade -y      # For Debian/Ubuntu
sudo yum update -y                          # For RHEL/CentOS

Tip: Remove any previously installed PostgreSQL packages to avoid version conflicts:

sudo apt remove --purge postgresql* -y     # Debian/Ubuntu
sudo yum remove postgresql* -y              # RHEL/CentOS

Step 2: Choose the Right PostgreSQL Version

The official Linux repositories often provide stable but sometimes outdated PostgreSQL versions. For the best performance and latest features, use the PostgreSQL Global Development Group (PGDG) repository.

Adding PGDG Repository (Debian/Ubuntu):

# Import the repository signing key
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

# Add PostgreSQL repository (replace `focal` with your Ubuntu version)
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ focal-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

# Update package lists again
sudo apt update

Adding PGDG Repository (RHEL/CentOS):

sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo yum -qy module disable postgresql

Step 3: Install PostgreSQL Server and Client

Once the repository is set:

# Debian/Ubuntu
sudo apt install -y postgresql postgresql-client

# RHEL/CentOS
sudo yum install -y postgresql14-server postgresql14

Replace postgresql14-server with the specific version you prefer.


Step 4: Initialize the Database Cluster

On Debian/Ubuntu systems, this usually happens automatically. But on RHEL/CentOS, you need to initialize manually:

sudo /usr/pgsql-14/bin/postgresql-14-setup initdb

Ensure the data directory (usually /var/lib/pgsql/14/data) is correctly initialized.


Step 5: Start and Enable PostgreSQL Service

Make sure PostgreSQL starts on boot and is running:

sudo systemctl enable postgresql
sudo systemctl start postgresql
sudo systemctl status postgresql

On RHEL/CentOS it might be:

sudo systemctl enable postgresql-14
sudo systemctl start postgresql-14
sudo systemctl status postgresql-14

Step 6: Secure PostgreSQL Installation

By default, PostgreSQL uses ‘peer’ authentication for local connections, requiring Linux user accounts to match PostgreSQL roles.

  • Switch to the postgres user:
sudo -i -u postgres
  • Access the PostgreSQL shell and create a secure password:
psql
ALTER USER postgres WITH PASSWORD 'StrongPasswordHere';
\q
  • Modify the authentication method to md5 (password-based) for remote connections, by editing pg_hba.conf:
sudo nano /etc/postgresql/14/main/pg_hba.conf   # Debian/Ubuntu path
sudo nano /var/lib/pgsql/14/data/pg_hba.conf   # RHEL/CentOS path

Change lines like:

host    all             all             127.0.0.1/32            md5
  • Reload PostgreSQL configuration:
sudo systemctl reload postgresql

Step 7: Test Your Installation

Validate that PostgreSQL is working:

psql -U postgres -W   # Enter the password when prompted

Create a test database and table:

CREATE DATABASE testdb;
\c testdb
CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(50), email VARCHAR(50));
INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');
SELECT * FROM users;

Step 8: Optimize PostgreSQL for Performance (Optional)

For production, tweak key configurations in postgresql.conf (location as above):

  • Increase shared memory:
shared_buffers = 1GB             # Set according to your RAM size
work_mem = 64MB
maintenance_work_mem = 256MB
checkpoint_completion_target = 0.9
wal_buffers = 16MB
  • Enable logging for better audit and troubleshooting:
logging_collector = on
log_directory = 'pg_log'
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
log_min_duration_statement = 500     # Logs queries longer than 500ms

After changes, reload PostgreSQL:

sudo systemctl reload postgresql

Common Pitfalls and Troubleshooting

  • Service won’t start: Check logs in /var/log/postgresql/ or /var/lib/pgsql/14/data/pg_log/.
  • Authentication failed: Confirm pg_hba.conf matches your intended authentication mode.
  • Port conflicts: PostgreSQL default port is 5432; ensure it’s free or change it in postgresql.conf.
  • Firewall blocks: Open port 5432 if remote access is needed:
sudo ufw allow 5432/tcp    # Debian/Ubuntu with UFW
sudo firewall-cmd --add-port=5432/tcp --permanent && sudo firewall-cmd --reload   # RHEL/CentOS

Wrap Up

Installing PostgreSQL on Linux is more than just running an install command—it's about setting the right foundation for stable, secure, and scalable database performance. By closely following these steps and tailoring configurations, you position yourself for success whether deploying small apps or enterprise-grade services.

Bookmark this guide as your go-to reference when setting up PostgreSQL environments on Linux — next time, you’ll have it mastered from start to finish!


If this walkthrough was helpful, share it with your network or drop a comment with your PostgreSQL setup tips and experiences!