How to Install PostgreSQL on Linux

How to Install PostgreSQL on Linux

If you’ve been putting off learning PostgreSQL because you weren’t sure how to get it running on your Linux machine, this guide is for you. I’ll walk through the entire installation process step by step, covering the most common Linux distributions, explaining what’s actually happening at each stage, and pointing out the mistakes that trip up most beginners. By the end, you’ll have a working PostgreSQL server, a basic understanding of how it’s structured on disk, and enough confidence to start creating databases and tables.

What Is PostgreSQL and Why Install It Yourself?

PostgreSQL (often just called “Postgres”) is a free, open-source relational database management system that’s been in active development since the late 1980s. It’s known for standards compliance, extensibility, and rock-solid reliability, which is why it powers everything from small side projects to massive production systems at companies like Instagram and Spotify.

Unlike some databases that only run well on a specific operating system, PostgreSQL was practically built with Linux in mind. Most production Postgres servers in the world run on Linux, so learning to install and manage it there is a genuinely useful, transferable skill — not just an academic exercise.

There are a few ways to get PostgreSQL onto a Linux box:

  • Installing from your distribution’s official package repositories
  • Installing from PostgreSQL’s own official repository (recommended if you want the latest version)
  • Compiling from source (rarely necessary unless you need a very custom build)
  • Running it inside a Docker container

I’ll cover the first two approaches in detail since they cover the vast majority of real-world use cases, and I’ll touch on Docker at the end for those who prefer a containerized setup.

Before You Start: Check Your Distribution

Run this command to confirm what distribution and version you’re on:

cat /etc/os-release

You’ll see output similar to:

NAME="Ubuntu"
VERSION="22.04.3 LTS (Jammy Jellyfish)"

Knowing your distro and version matters because package names and repository setup commands differ slightly between Debian-based systems (Ubuntu, Debian, Linux Mint) and RHEL-based systems (CentOS, Rocky Linux, AlmaLinux, Fedora).

Installing PostgreSQL on Ubuntu / Debian

Option 1: Using the Default Ubuntu/Debian Repository

This is the simplest method. It installs whatever version of PostgreSQL your distribution’s maintainers have packaged, which is usually stable but not always the newest release.

Update your package index first:

sudo apt update

Then install PostgreSQL along with the common contrib package (extra extensions and utilities):

sudo apt install postgresql postgresql-contrib -y

Once the install finishes, PostgreSQL should already be running as a background service. Verify with:

sudo systemctl status postgresql

You should see active (running) in the output. If not, start it manually:

sudo systemctl start postgresql
sudo systemctl enable postgresql

The enable command makes sure PostgreSQL starts automatically every time your server boots, which you’ll want for anything beyond a quick test.

Option 2: Using the Official PostgreSQL APT Repository (Latest Version)

If you want the most current PostgreSQL release rather than whatever ships with your distro, add PostgreSQL’s own repository.

First, import the signing key:

sudo apt install curl ca-certificates -y
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo gpg --dearmor -o /usr/share/keyrings/postgresql-keyring.gpg

Add the repository:

echo "deb [signed-by=/usr/share/keyrings/postgresql-keyring.gpg] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list

Update and install a specific version (17, at the time of writing, is current — adjust as needed):

sudo apt update
sudo apt install postgresql-17 postgresql-contrib-17 -y

This method is worth the extra steps if you need newer features, better performance improvements, or want to match a production environment that’s running a specific version.

Installing PostgreSQL on CentOS / RHEL / Rocky Linux / AlmaLinux

RHEL-based distributions typically ship with an older PostgreSQL version in their default repos, or none at all in some minimal installs. The official PostgreSQL Yum repository is the better route here.

First, install the repository RPM (adjust the version number and OS release to match your system — this example targets PostgreSQL 17 on RHEL/Rocky 9):

sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm

Disable the built-in PostgreSQL module so it doesn’t conflict with the official repo:

sudo dnf -qy module disable postgresql

Now install the server:

sudo dnf install -y postgresql17-server postgresql17-contrib

Unlike Debian-based installs, RHEL-based PostgreSQL doesn’t initialize the database cluster automatically. You need to do that manually:

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

Then start and enable the service:

sudo systemctl start postgresql-17
sudo systemctl enable postgresql-17

Check the status the same way as before:

sudo systemctl status postgresql-17

Installing PostgreSQL on Fedora

Fedora tends to have relatively current PostgreSQL packages in its default repos:

sudo dnf install postgresql-server postgresql-contrib -y
sudo postgresql-setup --initdb
sudo systemctl start postgresql
sudo systemctl enable postgresql

Installing PostgreSQL on Arch Linux

Arch users get a straightforward experience through pacman:

sudo pacman -S postgresql

Switch to the postgres system user to initialize the data directory:

sudo -iu postgres
initdb -D /var/lib/postgres/data
exit

Then start the service:

sudo systemctl start postgresql
sudo systemctl enable postgresql

Verifying Your Installation

Regardless of which distro you used, you should now confirm PostgreSQL is actually working. Switch to the postgres system user, which is created automatically during installation and owns the database cluster:

sudo -i -u postgres

From there, launch the interactive terminal, psql:

psql

You should land on a prompt that looks like:

postgres=#

Run a quick sanity check:

SELECT version();

You’ll see output confirming the installed PostgreSQL version, something like:

PostgreSQL 17.2 on x86_64-pc-linux-gnu, compiled by gcc...

Exit psql with:

\q

And return to your normal user with:

exit

Setting a Password for the postgres User

Fresh installs typically authenticate the postgres user through peer authentication (meaning only the matching Linux system user can log in without a password). If you plan to connect remotely or through applications, you’ll want a password.

Log back in as postgres and open psql:

sudo -u postgres psql

Set a password:

ALTER USER postgres WITH PASSWORD 'your_secure_password_here';

Replace the placeholder with something strong — never leave this as a default or weak value, especially on any machine reachable from outside your local network.

Creating a Regular Database User

Running everything as the postgres superuser is bad practice beyond initial setup. Create a dedicated user for your application or personal projects:

CREATE USER myuser WITH PASSWORD 'mypassword';

Grant that user the ability to create databases if needed:

ALTER USER myuser CREATEDB;

Allowing Remote Connections (Optional)

By default, PostgreSQL only listens on localhost, which is the safest configuration for most use cases. If you need to connect from another machine, two files need edits.

First, find PostgreSQL’s configuration directory. It’s usually at /etc/postgresql/<version>/main/ on Debian-based systems or /var/lib/pgsql/<version>/data/ on RHEL-based ones.

Edit postgresql.conf and change:

listen_addresses = 'localhost'

to:

listen_addresses = '*'

Then edit pg_hba.conf to allow the connection. Add a line like:

host    all             all             0.0.0.0/0               md5

This example is intentionally broad for illustration — in a real production setup, restrict the IP range to only the addresses that actually need access, and strongly consider requiring SSL connections instead of plain md5 password auth.

Restart PostgreSQL to apply the changes:

sudo systemctl restart postgresql

Also make sure your firewall allows traffic on PostgreSQL’s default port, 5432:

sudo ufw allow 5432/tcp

(Substitute firewall-cmd commands if you’re on a RHEL-based firewall setup.)

Installing PostgreSQL with Docker (Alternative Approach)

If you’d rather not install PostgreSQL directly on your host system — useful for testing, development, or running multiple isolated versions — Docker is a clean alternative.

Pull and run the official image:

docker run --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres:17

Connect to it using psql from inside the container:

docker exec -it my-postgres psql -U postgres

Docker is particularly handy for spinning up a disposable database for testing without touching your host system at all.

Common Installation Problems and How to Fix Them

“Peer authentication failed” when logging in as postgres. This happens when you try psql -U postgres as a regular Linux user instead of switching to the postgres system account first. Use sudo -u postgres psql, or configure pg_hba.conf to use password-based authentication instead of peer.

Service won’t start after installation. Check the logs for the actual error:

sudo journalctl -u postgresql -n 50

A common cause is a data directory that wasn’t properly initialized (common on RHEL-based systems where initdb needs to be run manually, as shown above).

Port 5432 already in use. This usually means another PostgreSQL instance (perhaps an older version, or a Docker container) is already bound to that port. Check with:

sudo lsof -i :5432

Can’t connect remotely even after editing configs. Double-check both postgresql.conf and pg_hba.conf were edited, the service was restarted (not just reloaded, if listen_addresses changed), and that your firewall and any cloud provider security groups also allow the port.

Best Practices After Installation

  • Never leave the postgres superuser with a blank or default password, especially on internet-facing servers.
  • Create separate database users with only the privileges they actually need, following the principle of least privilege.
  • Keep your pg_hba.conf as restrictive as possible — only open remote access when genuinely required, and prefer SSL/TLS for anything beyond localhost.
  • Set up regular backups early, before you actually need them. pg_dump is a good starting point for small to medium databases.
  • Keep PostgreSQL updated. Point releases contain security fixes and shouldn’t be skipped.
  • Monitor disk usage on the data directory — PostgreSQL can grow substantially depending on your workload.

Understanding the PostgreSQL Data Directory

Once installed, it helps to know where PostgreSQL actually stores everything. This location is often called PGDATA. On Debian-based systems it typically lives at /var/lib/postgresql/<version>/main, and on RHEL-based systems at /var/lib/pgsql/<version>/data.

Inside this directory you’ll find several important items:

  • postgresql.conf — the main server configuration file, controlling memory allocation, logging, connection limits, and dozens of other settings
  • pg_hba.conf — the host-based authentication file, which controls who can connect from where and using what authentication method
  • base/ — the actual data files for every database on the server
  • pg_wal/ — write-ahead log files, critical for crash recovery and replication

You generally won’t touch most of these directly, but knowing where they live makes troubleshooting far less mysterious when something goes wrong. For example, if PostgreSQL fails to start, the first place to look is the server log, often found at /var/log/postgresql/ on Debian-based systems.

Managing the PostgreSQL Service

Beyond starting and enabling the service, a few other systemctl commands are worth knowing for day-to-day administration:

sudo systemctl restart postgresql
sudo systemctl reload postgresql
sudo systemctl stop postgresql

restart fully stops and starts the process, which is necessary after changing settings like listen_addresses that can’t be applied while running. reload re-reads configuration files without dropping existing connections, which works for many settings like pg_hba.conf changes. Knowing the difference saves you from unnecessarily disconnecting active sessions when a lighter-touch reload would do.

On RHEL-based systems where the service name includes the version number, remember to substitute accordingly, e.g., sudo systemctl restart postgresql-17.

Configuring Basic Memory Settings

A fresh PostgreSQL install uses fairly conservative default memory settings, which are fine for testing but usually worth tuning once you’re running anything resembling real workloads. Two of the most impactful settings live in postgresql.conf:

shared_buffers = 256MB
work_mem = 4MB

shared_buffers controls how much memory PostgreSQL dedicates to caching data pages, and a common starting recommendation is roughly 25% of total system RAM on a dedicated database server. work_mem controls memory available per sort or hash operation within a query — too low, and complex queries spill to disk and slow down; too high, and many concurrent connections running memory-intensive queries can exhaust available RAM. These settings require a restart (for shared_buffers) or reload (for work_mem) to take effect, and tuning them properly depends on your actual hardware and workload, so treat any specific number as a starting point rather than a fixed rule.

Uninstalling PostgreSQL

Occasionally you’ll need to remove PostgreSQL entirely — to start fresh, switch versions, or decommission a server. On Debian-based systems:

sudo apt purge postgresql postgresql-contrib postgresql-*
sudo apt autoremove

The purge flag (rather than remove) also deletes configuration files, which matters if you want a completely clean slate. Note that this does not automatically delete the data directory in all cases — check /var/lib/postgresql/ afterward and remove it manually if you truly want everything gone:

sudo rm -rf /var/lib/postgresql/

On RHEL-based systems:

sudo dnf remove postgresql17-server postgresql17-contrib
sudo rm -rf /var/lib/pgsql/17/data

Be absolutely certain you’ve backed up anything important before running these commands — there’s no confirmation step, and the data directory removal is irreversible.

Upgrading PostgreSQL to a Newer Major Version

Major version upgrades (say, from PostgreSQL 15 to 17) aren’t handled automatically through a simple package update, because the on-disk data format can change between major versions. The standard tool for this is pg_upgrade, which comes bundled with PostgreSQL.

At a high level, the process looks like:

  1. Install the new major version alongside the old one (they can coexist, listening on different ports).
  2. Run pg_upgrade to migrate the data directory to the new version’s format.
  3. Update your service configuration to point at the new version.
  4. Run the analyze_new_cluster.sh script that pg_upgrade generates, to rebuild query planner statistics.
  5. Once confirmed working, remove the old version.

This is genuinely one of the more delicate PostgreSQL administration tasks, and it’s worth testing thoroughly on a staging copy of your data before doing it against production. Always take a full backup immediately before starting a major version upgrade, regardless of how confident you feel about the process.

Frequently Asked Questions

Which PostgreSQL version should I install? Unless you have a specific reason to match an older version (like compatibility with an existing production environment), install the latest stable major version. PostgreSQL has a well-established yearly release cycle, and each major version typically receives around five years of support.

Do I need postgresql-contrib? It’s not strictly required, but it bundles a number of genuinely useful extensions (like pgcrypto, pg_stat_statements, and uuid-ossp) that you’ll likely want at some point. Installing it upfront saves a separate install step later.

Can I run multiple PostgreSQL versions on the same machine? Yes — this is common during upgrades or when different projects require different versions. Each version listens on a different port by default (PostgreSQL typically increments from 5432), and RHEL-based installs in particular are designed to support this side-by-side pattern cleanly.

Is it safe to run PostgreSQL in a container for production use? Plenty of production deployments run PostgreSQL in containers successfully, but it requires careful attention to persistent storage (so data survives container restarts), resource limits, and backup strategy. For getting started, learning, and development, Docker is an excellent, low-friction option.

Wrapping Up

Getting PostgreSQL installed on Linux isn’t complicated once you know which path fits your distribution, but the details — initializing the data directory, setting a password, opening up remote access safely, understanding where configuration lives — are exactly where beginners tend to get stuck. Take the time to verify each step rather than rushing to the next command, and you’ll end up with a stable foundation to build on.

From here, the natural next steps are creating your first database, defining tables, and starting to write queries — which is exactly what the rest of this series covers.

Total
1
Shares

Leave a Reply

Previous Post
How to Create a Map Chart in Excel

How to Create a Map Chart in Excel

Next Post
How to Create a Database in PostgreSQL

How to Create a Database in PostgreSQL

Related Posts