11.2 Installing PostgreSQL
Table of Contents
Why Installation Matters
Before you can use PostgreSQL from your backend code, you need a running PostgreSQL server and the basic tools to connect to it. In this chapter you will:
- Install PostgreSQL on the 3 main platforms: Linux, macOS, and Windows
- Verify that the server is running
- Connect using the command line tool
psql - Create a test database and user
You do not need to be a system administration expert. You only need enough to get a local development database running.
Goal: By the end of this chapter you should be able to run psql, connect to a local PostgreSQL instance, and create a simple test database.
Installing PostgreSQL on Linux
On Linux, PostgreSQL is usually installed through your distribution package manager. The commands differ slightly between distributions, but the ideas are the same.
Ubuntu and Debian
On Ubuntu and Debian you can install PostgreSQL from the official PostgreSQL repository, which often has more recent versions than the default system repository.
Step 1: Add PostgreSQL repository
Open a terminal and run:
sudo apt update
sudo apt install curl ca-certificates gnupgAdd the PostgreSQL signing key and repository:
# Import the repository key
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
| sudo gpg --dearmor -o /usr/share/keyrings/postgresql.gpg
# Add the repository (for Ubuntu 22.04 as an example)
echo "deb [signed-by=/usr/share/keyrings/postgresql.gpg] \
http://apt.postgresql.org/pub/repos/apt jammy-pgdg main" \
| sudo tee /etc/apt/sources.list.d/pgdg.list
Change jammy to focal, bullseye, etc, depending on your distribution. You can find the correct codename on the PostgreSQL downloads page.
Step 2: Install PostgreSQL
Update and install:
sudo apt update
sudo apt install postgresql postgresql-contribpostgresqlis the serverpostgresql-contribincludes useful extra extensions
Step 3: Check service status
PostgreSQL should start automatically. Check:
sudo systemctl status postgresqlYou should see something like:
Active: active (exited) or active (running)If it is not running, start it:
sudo systemctl start postgresqlAnd enable on boot:
sudo systemctl enable postgresqlStep 4: Switch to the `postgres` system user
On Linux, PostgreSQL creates a special operating system user named postgres that owns the server process.
sudo -i -u postgresYour shell prompt should change to something like:
postgres@your-machine:~$
From here you can run psql without a password:
psql
To exit psql type:
\q
Then exit the postgres user:
exitCommon package commands (Ubuntu/Debian)
| Task | Command |
|---|---|
| Start PostgreSQL | sudo systemctl start postgresql |
| Stop PostgreSQL | sudo systemctl stop postgresql |
| Restart PostgreSQL | sudo systemctl restart postgresql |
| Status | sudo systemctl status postgresql |
| Version (server) | psql --version or postgres -V |
Fedora, CentOS, and RHEL
On Fedora and related distributions you usually use dnf or yum.
For a typical Fedora installation:
sudo dnf install postgresql-server postgresql-contribFor CentOS / RHEL, you might also need to initialize the database:
sudo /usr/bin/postgresql-setup --initdbThen start and enable the service:
sudo systemctl start postgresql
sudo systemctl enable postgresqlCheck status:
sudo systemctl status postgresql
Usage (switch user and run psql) is similar to Ubuntu:
sudo -i -u postgres
psqlInstalling PostgreSQL on macOS
On macOS you have several options. For development, two popular ones are:
- Homebrew
- PostgreSQL.app
Option 1: Homebrew
Homebrew is a package manager for macOS. It is a good choice if you like working in the terminal.
Step 1: Install Homebrew (if needed)
If you do not have Homebrew yet, run in Terminal:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Follow the instructions and then ensure brew is in your PATH as explained by the installer.
Step 2: Install PostgreSQL
brew update
brew install postgresqlHomebrew may print extra instructions at the end, read them carefully. They often include helpful tips about managing the service.
Step 3: Start the PostgreSQL service
brew services start postgresqlCheck that it is running:
brew services list
You should see postgresql with status started.
Step 4: Test `psql`
PostgreSQL client tools are now available in your shell.
psql --versionTo connect to the default database with your macOS username:
psql postgresIf everything works, you will see a prompt similar to:
postgres=#
Type \q to exit.
Option 2: PostgreSQL.app
PostgreSQL.app is a standalone app that includes PostgreSQL and common tools, convenient if you want a more graphical and self-contained installation.
- Go to https://postgresapp.com
- Download the latest version for your macOS
- Drag and drop PostgreSQL.app into your Applications folder
- Open PostgreSQL.app. It will initialize and start a PostgreSQL server
To use psql from the terminal, PostgreSQL.app offers a menu item:
- Open PostgreSQL.app
- Click the gear icon
- Choose “Open psql” or “Copy psql command”
- Or add its bin directory to your
PATHas described in the documentation
Installing PostgreSQL on Windows
On Windows, the easiest way is the official installer provided by EnterpriseDB.
Step 1: Download the installer
- Go to https://www.postgresql.org/download/windows/
- Click the link to installers provided by EnterpriseDB
- Download the latest stable version (for example, 16.x) for Windows
You will get an .exe installer file.
Step 2: Run the installer
Double click the installer and follow the wizard:
- Installation directory: choose a location, or accept the default, for example
C:\Program Files\PostgreSQL\16\ - Components: select at least:
- PostgreSQL Server
- pgAdmin 4 (graphical admin tool)
- Command Line Tools
- Data directory: accept the default or pick a location
- Password: set a strong password for the PostgreSQL superuser
postgres. Write it down, you will need it later - Port: default is
5432. Normally you should keep this - Locale: choose your locale or accept default
Finish the installation. The installer will start the PostgreSQL service.
Step 3: Verify service status
On Windows, PostgreSQL runs as a Windows service.
- Press
Win + R - Type
services.mscand press Enter - Look for a service named like:
postgresql-x64-16or similar - The status should be “Running”
If it is not running, right click the service and choose “Start”.
Step 4: Test connectivity with `psql`
You can use either:
- Windows Command Prompt
- PowerShell
- The “SQL Shell (psql)” shortcut that the installer usually adds
Example using “SQL Shell (psql)”:
- Open the Start menu
- Search for “SQL Shell (psql)” and open it
- It will ask:
Server [localhost]:
Database [postgres]:
Port [5432]:
Username [postgres]:Press Enter for Server, Database, Port, then type:
Username: postgresThen type the password you set in the installer.
If login is successful, you will see the postgres=# prompt.
Type:
SELECT version();Then:
\qto exit.
Verifying Your Installation
After installation on any platform, you should check two things:
- The server is running
- You can connect with
psql
Check the server status
Linux
sudo systemctl status postgresql
You want active (running) or similar.
macOS with Homebrew
brew services list
Look for postgresql started.
Windows
Use services.msc and check that the PostgreSQL service is running.
Check `psql` version
Run this in your terminal or command prompt:
psql --versionYou should see output similar to:
psql (PostgreSQL) 16.0
If your system says command not found or similar, then psql is not in your PATH or not installed. For:
- Linux: ensure
postgresql-clientis installed, or thepostgresqlpackage itself - macOS Homebrew: ensure the Homebrew bin directory is in your
PATH - PostgreSQL.app: add its bin directory to your
PATHas described in the app - Windows: ensure you installed Command Line Tools and restarted your terminal
Basic `psql` Usage
Once PostgreSQL is installed, psql is the main command line tool you will use to:
- Run SQL queries
- Create databases and users
- Inspect schemas, tables, and more
You do not need to memorize everything now. Just learn the basic commands you will use daily.
Connecting to PostgreSQL
The connection syntax is:
psql -h HOST -p PORT -U USERNAME -d DATABASEIf you omit some options, it will use defaults:
- Host:
localhost - Port:
5432 - Username: your operating system username (sometimes)
- Database: same as username, or
postgres
Examples
Linux (as postgres OS user):
sudo -i -u postgres
psqlmacOS with your system user:
psql postgresWindows:
psql -U postgres -d postgres -h localhost -p 5432
When prompted for a password, type it and press Enter. psql shows nothing as you type, this is normal.
Useful `psql` meta commands
psql commands start with a backslash. They are not SQL, they are client commands.
| Command | Description |
|---|---|
\q | Exit psql |
\l | List databases |
\c db | Connect to database db |
\dt | List tables in current database |
\du | List roles (users) |
\d table_name | Describe table structure |
\? | Help for meta commands |
Example:
\l
\c postgres
\dt
\duCreating a Test Database and User
You now have PostgreSQL running. For backend development, you typically do not use the default superuser from your application. Instead, you create:
- A database for your project
- A user (role) with a password
- Permissions for that user on the database
Rule: Never use the postgres superuser from your application. Always create a separate, limited user for each application.
Step 1: Connect as an admin
On Linux, run:
sudo -i -u postgres
psql
On macOS / Windows, connect as postgres (superuser) using psql:
psql -U postgres -d postgres -h localhostEnter the password if prompted.
You should see the postgres=# prompt.
Step 2: Create a database
Create a new database named myapp_dev:
CREATE DATABASE myapp_dev;Check that it exists:
\l
You should see myapp_dev in the list.
Step 3: Create a user with password
Create a login role that your backend application will use.
Example user myapp_user with password myapp_password:
CREATE USER myapp_user WITH PASSWORD 'myapp_password';For development, this is fine. For production, you should use a stronger password and secure storage, which you will cover in later chapters.
Step 4: Grant privileges on the database
Give the new user permission to work with the new database.
First, connect to the database:
\c myapp_devYou will see:
You are now connected to database "myapp_dev"Then grant privileges:
GRANT ALL PRIVILEGES ON DATABASE myapp_dev TO myapp_user;At this point:
myapp_devis a new databasemyapp_usercan connect to it and create tables
Step 5: Test login as the new user
Exit psql:
\q
Connect again using myapp_user:
psql -U myapp_user -d myapp_dev -h localhost
Enter the password myapp_password.
Now create a simple table to confirm permissions:
CREATE TABLE test_table (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
INSERT INTO test_table (name) VALUES ('hello'), ('postgres');
SELECT * FROM test_table;You should see:
id | name
----+---------
1 | hello
2 | postgres
(2 rows)
Then type \q to exit.
Typical Connection Details for Backend Apps
Your backend application will usually need the following fields to connect to PostgreSQL:
| Field | Typical development value |
|---|---|
| Host | localhost |
| Port | 5432 |
| Database | myapp_dev |
| User | myapp_user |
| Password | myapp_password |
In many backend frameworks, you will configure a database URL like:
postgresql://myapp_user:myapp_password@localhost:5432/myapp_devLater chapters will show how to use this with ORMs and FastAPI.
Common Installation Problems and Fixes
You might run into some typical problems. Here are simple checks.
Port already in use
If another PostgreSQL instance or service uses port 5432, you might see errors like:
could not bind IPv4 socket: Address already in useSolutions:
- Stop the other PostgreSQL service
- Change the port in
postgresql.confand restart - On Linux, inspect which process uses the port:
sudo lsof -i :5432Cannot connect: “connection refused”
Check that the service is running:
- Linux:
sudo systemctl status postgresql - macOS Homebrew:
brew services list - Windows:
services.msc
If it is stopped, start it.
Authentication failed
Errors like:
psql: FATAL: password authentication failed for user "myapp_user"Possible issues:
- Wrong password
- User does not exist
- Using the wrong host or port
You can reset the password as superuser:
ALTER USER myapp_user WITH PASSWORD 'new_password';Then try again.
Summary
You now know how to:
- Install PostgreSQL on Linux, macOS, and Windows
- Start and stop the PostgreSQL service
- Use
psqlto connect to the server - Create a dedicated database and user for your application
- Confirm everything works with a simple test table
This setup is enough for development work. In later chapters you will learn how to design schemas, use SQL, and connect PostgreSQL to your backend code using ORMs and connection URLs.
Views: 8
KAHIBARO