Database

How to Install PostgreSQL on WSL Ubuntu 22.04

This guide covers how to install PostgreSQL on WSL Ubuntu 22.04, create a database and user, and verify everything works with a Python connection…

How to Install PostgreSQL on WSL Ubuntu 22.04
Share:

How to Install PostgreSQL on WSL Ubuntu 22.04

4 min read
1.1K views

This guide covers how to install PostgreSQL on WSL Ubuntu 22.04, create a database and user, and verify everything works with a Python connection test. The examples are run on WSL2 Ubuntu in Windows, but they work the same on any Ubuntu 22.04 system.

Ubuntu 22.04’s default repositories include PostgreSQL 14; Ubuntu 24.04 includes PostgreSQL 16. The optional repository section below installs PostgreSQL 18 explicitly. If you need a newer version (such as 18), I’ll show you how to add the official PostgreSQL repository as well.

Advertisement

Prerequisites

Install PostgreSQL on WSL Ubuntu

Step 1: Update Package Lists

sudo apt update

Step 2: Install PostgreSQL

sudo apt install postgresql postgresql-contrib -y

The postgresql-contrib package includes extra utilities and extensions like pg_stat_statements and uuid-ossp that you’ll probably want later. The installation automatically creates a postgres system user.

Step 3: Start PostgreSQL

Current Ubuntu WSL installations use systemd by default. Check PID 1 with ps -p 1 -o comm=. If it prints systemd, enable PostgreSQL for distro startup and start it now:

sudo systemctl enable --now postgresql

On older WSL installations without systemd, start it manually with sudo service postgresql start, or enable systemd using Microsoft’s instructions. Do not add sudo service commands to .bashrc. Enabled services start when the distro boots; they do not keep a stopped WSL instance alive.

Advertisement

Step 4: Verify It’s Running

pg_lsclusters

You should see something like 14/main (port 5432): online.

Create a Database and User

First, switch to the postgres system user and open the PostgreSQL shell:

sudo -i -u postgres
psql

Create the role first, then a database owned by it. On PostgreSQL 15 and later, database-level grants alone do not grant CREATE in the public schema; see schema privileges:

CREATE USER myuser WITH ENCRYPTED PASSWORD 'your_password_here';
CREATE DATABASE mydb OWNER myuser;

A few settings that are good practice for new roles: especially if you’re working with Django or similar frameworks:

ALTER ROLE myuser SET client_encoding TO 'utf8';
ALTER ROLE myuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE myuser SET timezone TO 'UTC';

Useful psql Commands

Command What It Does
\l List all databases
\du List all users/roles
\dt List tables in current database
\c mydb Connect to a specific database
\q Exit psql

To exit back to your regular user, type \q to leave psql, then exit to leave the postgres shell.

Installing a Newer PostgreSQL Version (Optional)

Ubuntu 22.04 ships with PostgreSQL 14. If you need a newer major such as 18, add the official PostgreSQL APT repository:

sudo apt install -y curl ca-certificates
sudo install -d /usr/share/postgresql-common/pgdg
sudo curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list
sudo apt update

Then install the version you want:

# Install PostgreSQL 18
sudo apt install -y postgresql-18

# Or PostgreSQL 16
sudo apt install -y postgresql-16

If you already have PostgreSQL 14 installed, both versions will run side by side on different ports. Check which clusters are running with:

pg_lsclusters

Test the Connection with Python

A quick way to verify your setup is working: connect to the database from a Python script using psycopg2.

Install the required packages. If you manage Python versions with pyenv, see How to Install and manage Python Versions on WSL Ubuntu.

sudo apt install -y python3-venv
python3 -m venv .venv
source .venv/bin/activate
python -m pip install psycopg2-binary

The Psycopg binary wheel needs no libpq development headers. Headers and a compiler are needed for source builds. This venv also avoids Ubuntu 24.04’s PEP 668 restriction. Keep it activated for the test; use the port shown by pg_lsclusters if it differs from 5432.

Create a test script test_pg.py:

import psycopg2
from psycopg2 import OperationalError

def test_connection():
    try:
        conn = psycopg2.connect(
            host="localhost",
            port=5432,
            database="mydb",
            user="myuser",
            password="your_password_here"
        )
        print("Connection successful")
        conn.close()
    except OperationalError as e:
        print(f"Connection failed: {e}")

if __name__ == "__main__":
    test_connection()
python3 test_pg.py

If you see Connection successful, you’re good. If you get an authentication error, double-check the username, password, and database name you created earlier.

Conclusion

PostgreSQL is up and running on your WSL Ubuntu. From here, you can connect to it from your applications, use it as a local dev database, or start learning SQL.

If you want a GUI to manage your databases, check out How to Access PostgreSQL in Ubuntu WSL with pgAdmin 4. And if you’re ready to write queries, How to Use SQL Joins and Conditional Statements in PostgreSQL is a good next step.

Recommended for Linux builders

Contabo VPS hosting for Linux projects

Run Linux servers, automation tools, and self-hosted apps on a Contabo VPS with generous resources and predictable pricing.

Our customers sayExcellent4.6 out of 5 based on 11,008 reviews Trustpilot

Some links are affiliate links. This may earn LinuxBeast a commission at no extra cost to you.

Privacy settings

Choose which privacy controls to open.

Opening these controls does not change your saved choices.