
How to Install PostgreSQL on Ubuntu 24 – Quickstart Guide
PostgreSQL is a powerful, open-source object-relational database system that’s become a go-to choice for developers and sysadmins who need robust data management capabilities. Whether you’re building a web application, setting up analytics infrastructure, or migrating from MySQL, getting PostgreSQL running on Ubuntu 24 is straightforward once you know the right steps. This guide walks you through the complete installation process, from adding repositories to configuring your first database, plus troubleshooting tips for the most common hiccups you’ll encounter.
Understanding PostgreSQL Installation Methods
Ubuntu 24 gives you several ways to install PostgreSQL, each with distinct advantages depending on your use case. The default Ubuntu repositories include PostgreSQL packages, but they’re often a few versions behind. For production environments or when you need the latest features, the official PostgreSQL APT repository is typically your best bet.
Installation Method | PostgreSQL Version | Update Frequency | Best For |
---|---|---|---|
Ubuntu Default Repos | Usually 14-15 | Ubuntu release cycle | Quick testing, development |
Official PostgreSQL APT | Latest (16+) | Regular updates | Production, latest features |
Docker Container | Any version | As needed | Containerized deployments |
Source Compilation | Latest/Custom | Manual | Custom configurations |
Quick Installation Using Ubuntu Repositories
If you just need PostgreSQL up and running fast for development work, the Ubuntu repository method is dead simple:
sudo apt update
sudo apt install postgresql postgresql-contrib
This installs PostgreSQL along with additional utilities and extensions. The postgresql-contrib
package includes extra modules like pg_stat_statements
and uuid-ossp
that you’ll probably want later.
After installation, PostgreSQL automatically starts and creates a system user called postgres
. Switch to this user to access the database:
sudo -i -u postgres
psql
You’ll see the PostgreSQL prompt where you can run SQL commands. Type \q
to exit.
Installing Latest PostgreSQL from Official Repository
For production environments or when you need newer features, install from the official PostgreSQL APT repository. This method ensures you get the latest stable version with regular security updates.
First, install the required packages and add the PostgreSQL signing key:
sudo apt update
sudo apt install -y wget ca-certificates
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
Add the official PostgreSQL repository to your sources list:
echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list
Update the package list and install PostgreSQL:
sudo apt update
sudo apt install postgresql-16 postgresql-client-16
Replace “16” with whatever version you want. You can see available versions with:
apt-cache search postgresql | grep postgresql-[0-9]
Initial Configuration and Security Setup
Fresh PostgreSQL installations come with minimal configuration that works for local development but needs hardening for anything beyond that. The default setup creates a postgres
superuser with no password, accessible only via local Unix socket authentication.
First, set a password for the postgres user:
sudo -u postgres psql
ALTER USER postgres PASSWORD 'your_secure_password_here';
\q
Create a database and user for your application:
sudo -u postgres createdb myapp_db
sudo -u postgres psql
CREATE USER myapp_user WITH ENCRYPTED PASSWORD 'another_secure_password';
GRANT ALL PRIVILEGES ON DATABASE myapp_db TO myapp_user;
\q
The main PostgreSQL configuration files live in /etc/postgresql/[version]/main/
:
postgresql.conf
– Main configuration file for server settingspg_hba.conf
– Client authentication configurationpg_ident.conf
– User name mapping (rarely needed)
For remote connections, edit postgresql.conf
and change:
listen_addresses = 'localhost'
To:
listen_addresses = '*'
Then modify pg_hba.conf
to allow connections. Add this line for password authentication from specific networks:
host all all 192.168.1.0/24 md5
Restart PostgreSQL to apply changes:
sudo systemctl restart postgresql
Performance Tuning and Optimization
Default PostgreSQL settings are conservative and work poorly for most real-world workloads. Here are the key parameters you should adjust based on your server specifications:
Parameter | Default | Recommended (8GB RAM) | Purpose |
---|---|---|---|
shared_buffers | 128MB | 2GB | Database cache memory |
effective_cache_size | 4GB | 6GB | OS cache size estimate |
work_mem | 4MB | 64MB | Memory per sort/hash operation |
maintenance_work_mem | 64MB | 512MB | Memory for VACUUM, CREATE INDEX |
Edit /etc/postgresql/16/main/postgresql.conf
and adjust these values. The PGTune website can generate optimized settings based on your hardware specs.
Enable performance monitoring by adding these lines:
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all
pg_stat_statements.max = 10000
After restarting PostgreSQL, create the extension in your database:
sudo -u postgres psql -d myapp_db
CREATE EXTENSION pg_stat_statements;
\q
Common Issues and Troubleshooting
Even straightforward PostgreSQL installations can hit snags. Here are the most frequent problems and their solutions:
Connection refused errors: Usually means PostgreSQL isn’t running or listening on the expected port. Check the service status:
sudo systemctl status postgresql
sudo systemctl start postgresql
Verify it’s listening on port 5432:
sudo netstat -tlnp | grep 5432
Authentication failures: PostgreSQL’s authentication can be confusing. Check pg_hba.conf
for the correct authentication method. The order of entries matters – PostgreSQL uses the first matching rule.
Permission denied for database creation: Make sure your user has the CREATEDB privilege:
sudo -u postgres psql
ALTER USER myapp_user CREATEDB;
\q
Disk space issues: PostgreSQL writes heavily to disk. Monitor space usage and set up log rotation:
sudo du -sh /var/lib/postgresql/
sudo journalctl -u postgresql -f
Port conflicts: If port 5432 is already in use, change it in postgresql.conf
:
port = 5433
Real-World Use Cases and Integration Examples
PostgreSQL shines in scenarios where data integrity and advanced features matter more than raw speed. Here are some practical integration examples:
Web Application Backend: For a typical Django or Rails app, you’ll want connection pooling. Install and configure pgBouncer:
sudo apt install pgbouncer
sudo nano /etc/pgbouncer/pgbouncer.ini
Basic pgBouncer configuration:
[databases]
myapp_db = host=localhost port=5432 dbname=myapp_db
[pgbouncer]
listen_port = 6432
listen_addr = localhost
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 100
default_pool_size = 25
Analytics Workload: PostgreSQL handles analytical queries well, especially with proper indexing. Create a columnar index for time-series data:
CREATE INDEX CONCURRENTLY idx_events_timestamp
ON events USING BRIN (created_at);
JSON/NoSQL Hybrid: PostgreSQL’s JSONB support lets you combine relational and document approaches:
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
metadata JSONB
);
CREATE INDEX idx_products_metadata
ON products USING GIN (metadata);
Comparison with Alternative Databases
Understanding when to choose PostgreSQL over alternatives helps justify the installation effort:
Database | Best For | PostgreSQL Advantage | Migration Difficulty |
---|---|---|---|
MySQL | Simple web apps, WordPress | Better JSON support, window functions | Low |
MongoDB | Rapid prototyping, flexible schemas | ACID compliance, SQL queries | High |
SQLite | Mobile apps, embedded systems | Concurrent writes, network access | Low |
Oracle | Enterprise applications | No licensing costs, similar features | Medium |
PostgreSQL particularly excels when you need complex queries, data integrity guarantees, or plan to scale beyond simple CRUD operations. The extensibility through custom data types and functions makes it suitable for specialized applications like geospatial analysis with PostGIS.
Best Practices for Production Deployments
Running PostgreSQL in production requires additional considerations beyond the basic installation. Set up automated backups immediately:
sudo mkdir -p /backup/postgresql
sudo chown postgres:postgres /backup/postgresql
# Create backup script
sudo nano /usr/local/bin/pg_backup.sh
Backup script content:
#!/bin/bash
BACKUP_DIR="/backup/postgresql"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME="myapp_db"
pg_dump -U postgres -h localhost $DB_NAME | gzip > $BACKUP_DIR/backup_${DB_NAME}_${DATE}.sql.gz
# Keep only last 7 days of backups
find $BACKUP_DIR -name "backup_*.sql.gz" -mtime +7 -delete
Make it executable and add to cron:
sudo chmod +x /usr/local/bin/pg_backup.sh
sudo crontab -e
Add this line for daily backups at 2 AM:
0 2 * * * /usr/local/bin/pg_backup.sh
Monitor PostgreSQL performance with built-in views:
-- Check active connections
SELECT count(*) FROM pg_stat_activity;
-- Find slow queries
SELECT query, mean_time, calls FROM pg_stat_statements
ORDER BY mean_time DESC LIMIT 10;
-- Check database sizes
SELECT datname, pg_size_pretty(pg_database_size(datname))
FROM pg_database;
For high-availability setups on your VPS or dedicated server, consider implementing streaming replication or logical replication depending on your needs. The official PostgreSQL documentation covers these advanced topics comprehensively.
Regular maintenance tasks should be automated. PostgreSQL’s autovacuum handles most cleanup, but you might need manual intervention for heavily updated tables:
-- Check table bloat
SELECT schemaname, tablename, n_dead_tup, n_live_tup,
round(n_dead_tup * 100.0 / (n_live_tup + n_dead_tup), 2) AS dead_ratio
FROM pg_stat_user_tables
WHERE n_dead_tup > 1000
ORDER BY dead_ratio DESC;
This setup gives you a solid PostgreSQL foundation that can handle serious workloads while remaining maintainable. The combination of proper configuration, monitoring, and backups will save you from most database disasters down the road.

This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.
This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.