Installation_setup
Chapter 2: Installation & Configuration
Section titled “Chapter 2: Installation & Configuration”Setting Up PostgreSQL for Development and Production
Section titled “Setting Up PostgreSQL for Development and Production”2.1 Installation Methods Overview
Section titled “2.1 Installation Methods Overview” PostgreSQL Installation Methods ========================================================================
Start: Install PostgreSQL | v +-----------------------+ | What's your platform?| +-----------+-----------+ | +-------------+--------------+-------------+-------------+ | | | | | v v v v v Linux macOS Windows Docker Cloud (YUM/APT) (Brew) (Installer) (Container) (RDS/Azul) | | | | | v v v v v ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌─────────┐ │Binary │ │Binary │ │Installer │ │Official │ │Managed │ │Packages │ │Packages │ │or ZIP │ │Images │ │Service │ │(apt/yum) │ │(brew) │ │ │ │ │ │ │ └───────────┘ └───────────┘ └───────────┘ └───────────┘ └─────────┘ ========================================================================2.2 Linux Installation (Ubuntu/Debian)
Section titled “2.2 Linux Installation (Ubuntu/Debian)”Installing PostgreSQL from APT Repository
Section titled “Installing PostgreSQL from APT Repository”# Step 1: Create the file repository configurationsudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
# Step 2: Import the repository signing keywget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
# Step 3: Update the package listssudo apt-get update
# Step 4: Install PostgreSQLsudo apt-get install postgresql-17 postgresql-client-17
# Step 5: Verify installationpsql --version# Output: psql (PostgreSQL) 17.x.xAlternative: Install from Default Repository
Section titled “Alternative: Install from Default Repository”# Ubuntu 22.04+ and Debian 12+ have PostgreSQL 14+ in default repossudo apt updatesudo apt install postgresql postgresql-contrib
# Check versionpsql --version2.3 Linux Installation (RHEL/CentOS/Fedora)
Section titled “2.3 Linux Installation (RHEL/CentOS/Fedora)”Using YUM/DNF Repository
Section titled “Using YUM/DNF Repository”# For RHEL/CentOS 8+ or Fedorasudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
# Install PostgreSQL server and clientsudo dnf install postgresql17-server postgresql17
# Initialize the database (first time only)sudo /usr/pgsql-17/bin/postgresql-17-setup initdb
# Start and enable PostgreSQLsudo systemctl start postgresql-17sudo systemctl enable postgresql-17
# Check statussudo systemctl status postgresql-17
# Open firewall (if enabled)sudo firewall-cmd --permanent --add-service=postgresqlsudo firewall-cmd --reload2.4 macOS Installation
Section titled “2.4 macOS Installation”Using Homebrew
Section titled “Using Homebrew”# Install PostgreSQLbrew install postgresql@17
# Start PostgreSQL as a servicebrew services start postgresql@17
# Or run it manually (not as a service)pg_ctl -D /opt/homebrew/var/postgresql@17 start
# Verify installationpsql --version
# Stop PostgreSQL (if needed)brew services stop postgresql@17Using PostgreSQL.app
Section titled “Using PostgreSQL.app”# Download from https://postgresapp.com/# Or install via Homebrew (older method)brew install --cask postgres
# After installation, add to PATH# Add to ~/.zshrc or ~/.bash_profile:export PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH"2.5 Windows Installation
Section titled “2.5 Windows Installation”Using Interactive Installer
Section titled “Using Interactive Installer”Windows Installation Steps:===========================
1. Download installer from: https://www.postgresql.org/download/windows/
2. Run the installer (postgresql-17.x-windows-x64.exe)
3. Installation Wizard: ┌────────────────────────────────────────────┐ │ Welcome to PostgreSQL Setup │ │ │ │ [Next] │ └────────────────────────────────────────────┘
┌────────────────────────────────────────────┐ │ Installation Directory: │ │ C:\Program Files\PostgreSQL\17 │ │ │ │ [Next] │ └────────────────────────────────────────────┘
┌────────────────────────────────────────────┐ │ Select Components: │ │ ☑ PostgreSQL Server │ │ ☑ pgAdmin 4 │ │ ☑ Command Line Tools │ │ ☑ Stack Builder │ │ │ │ [Next] │ └────────────────────────────────────────────┘
┌────────────────────────────────────────────┐ │ Data Directory: │ │ C:\Program Files\PostgreSQL\17\data │ │ │ │ [Next] │ └────────────────────────────────────────────┘
┌────────────────────────────────────────────┐ │ Set Password for 'postgres' superuser: │ │ Password: ************ │ │ Confirm: ************ │ │ │ │ [Next] │ └────────────────────────────────────────────┘
┌────────────────────────────────────────────┐ │ Port: 5432 (default) │ │ │ │ [Next] │ └────────────────────────────────────────────┘
┌────────────────────────────────────────────┐ │ Advanced Options: │ │ Locale: [Default locale] │ │ │ │ [Next] │ └────────────────────────────────────────────┘
┌────────────────────────────────────────────┐ │ Pre-Installation Summary │ │ │ │ [Next] │ └────────────────────────────────────────────┘
┌────────────────────────────────────────────┐ │ Installing... │ │ ████████████████░░░░░░░░░░░░░░░░░░░░░░░ │ │ │ │ Complete! │ └────────────────────────────────────────────┘2.6 Docker Installation
Section titled “2.6 Docker Installation”Running PostgreSQL in Docker
Section titled “Running PostgreSQL in Docker”# Pull the official PostgreSQL imagedocker pull postgres:17
# Run PostgreSQL containerdocker run \ --name my-postgres \ -e POSTGRES_PASSWORD=mysecretpassword \ -e POSTGRES_DB=mydb \ -p 5432:5432 \ -v postgres-data:/var/lib/postgresql/data \ postgres:17
# Run with custom configurationdocker run \ --name my-postgres \ -e POSTGRES_PASSWORD=mysecretpassword \ -e POSTGRES_DB=mydb \ -p 5432:5432 \ -v /path/to/postgresql.conf:/etc/postgresql/postgresql.conf \ -v postgres-data:/var/lib/postgresql/data \ postgres:17 \ -c config_file=/etc/postgresql/postgresql.conf
# Connect to the containerdocker exec -it my-postgres psql -U postgres
# Docker Compose exampleDocker Compose Configuration
Section titled “Docker Compose Configuration”version: '3.8'
services: postgres: image: postgres:17 container_name: my-postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: mysecretpassword POSTGRES_DB: mydb ports: - "5432:5432" volumes: - postgres-data:/var/lib/postgresql/data - ./backup:/backup healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s timeout: 5s retries: 5
volumes: postgres-data:# Start the containersdocker-compose up -d
# Stop containersdocker-compose down
# View logsdocker-compose logs -f postgres2.7 Cloud PostgreSQL Services
Section titled “2.7 Cloud PostgreSQL Services”Amazon RDS for PostgreSQL
Section titled “Amazon RDS for PostgreSQL”# Create RDS PostgreSQL instance via AWS CLIaws rds create-db-instance \ --db-instance-identifier my-postgres-instance \ --db-instance-class db.t3.micro \ --engine postgres \ --engine-version 17.4 \ --allocated-storage 20 \ --master-username postgres \ --master-user-password mypassword123 \ --vpc-security-group-ids sg-0123456789abcdef0 \ --db-subnet-group-name my-subnet-group \ --backup-retention-period 7 \ --multi-az
# Connect to RDS PostgreSQLpsql -h my-postgres-instance.xxxx.us-east-1.rds.amazonaws.com -U postgres -p 5432Azure Database for PostgreSQL
Section titled “Azure Database for PostgreSQL”# Create Azure PostgreSQL serveraz postgres server create \ --resource-group myresourcegroup \ --name mypostgreserver \ --sku-name B_Gen5_1 \ --location eastus \ --admin-user postgresadmin \ --admin-password mypassword123 \ --ssl-enforcement Enabled
# Configure firewallaz postgres server firewall-rule create \ --resource-group myresourcegroup \ --server mypostgreserver \ --name AllowMyIP \ --start-ip-address 0.0.0.0 \ --end-ip-address 255.255.255.255
# Connectpsql -h mypostgreserver.postgres.database.azure.com -U postgresadmin -p 5432Google Cloud SQL
Section titled “Google Cloud SQL”# Create Cloud SQL PostgreSQL instancegcloud sql instances create my-postgres-instance \ --database-version=POSTGRES_17 \ --tier=db-f1-micro \ --region=us-central1
# Set passwordgcloud sql users set-password postgres \ --instance=my-postgres-instance \ --password=mypassword123
# Connectgcloud sql connect my-postgres-instance --user=postgres2.8 PostgreSQL Configuration
Section titled “2.8 PostgreSQL Configuration”Understanding Configuration Files
Section titled “Understanding Configuration Files” PostgreSQL Configuration Files ========================================================================
Configuration File Location: ============================
Linux: /etc/postgresql/17/main/postgresql.conf macOS: /opt/homebrew/var/postgresql@17/postgresql.conf Windows: C:\Program Files\PostgreSQL\17\data\postgresql.conf Docker: /etc/postgresql/postgresql.conf
┌─────────────────────────────────────────────────────────────────────┐ │ Configuration Hierarchy │ │ │ │ 1. postgresql.conf - Main configuration │ │ 2. postgresql.auto.conf - ALTER SYSTEM settings (overrides) │ │ 3. pg_hba.conf - Client authentication │ │ 4. pg_ident.conf - User name mapping │ │ │ └─────────────────────────────────────────────────────────────────────┘
========================================================================Essential postgresql.conf Settings
Section titled “Essential postgresql.conf Settings”# Memory settingsshared_buffers = 256MB # 25% of RAM, max 8GBeffective_cache_size = 768MB # 75% of RAMwork_mem = 64MB # Per sort/hash operationmaintenance_work_mem = 256MB # For VACUUM, CREATE INDEXwal_buffers = 16MB # WAL buffer size
# Query planningrandom_page_cost = 1.1 # For SSD storageeffective_io_concurrency = 200 # Parallel I/O operationsdefault_statistics_target = 100 # Statistics collection
# Write-Ahead Log (WAL)wal_level = replica # minimal, replica, or logicalmax_wal_senders = 10 # Replication sendersmax_replication_slots = 10 # Replication slotswal_keep_size = 1GB # WAL files to keep
# Logginglog_destination = 'stderr'logging_collector = onlog_directory = 'log'log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'log_min_duration_statement = 1000 # Log queries > 1 second
# Connection settingslisten_addresses = '*' # Listen on all interfacesport = 5432max_connections = 100pg_hba.conf - Authentication Configuration
Section titled “pg_hba.conf - Authentication Configuration”# TYPE DATABASE USER ADDRESS METHOD
# Local connectionslocal all all peer
# IPv4 local connectionshost all all 127.0.0.1/32 scram-sha-256
# IPv6 local connectionshost all all ::1/128 scram-sha-256
# Allow replication connectionslocal replication all peerhost replication all 127.0.0.1/32 scram-sha-256host replication all ::1/128 scram-sha-256
# Production: Allow specific application servershost myapp myapp 10.0.0.0/8 scram-sha-256
# Development: Allow allhost all all 0.0.0.0/0 scram-sha-256host all all ::/0 scram-sha-2562.9 Managing PostgreSQL Services
Section titled “2.9 Managing PostgreSQL Services”Starting, Stopping, and Restarting
Section titled “Starting, Stopping, and Restarting”# Systemd (Linux)# Start PostgreSQLsudo systemctl start postgresql
# Stop PostgreSQLsudo systemctl stop postgresql
# Restart PostgreSQLsudo systemctl restart postgresql
# Reload configuration (without restart)sudo systemctl reload postgresql
# Check statussudo systemctl status postgresql
# Enable on bootsudo systemctl enable postgresql
# Disable on bootsudo systemctl disable postgresql
# Using pg_ctl (all platforms)# Startpg_ctl -D /var/lib/postgresql/data start
# Stoppg_ctl -D /var/lib/postgresql/data stop
# Restartpg_ctl -D /var/lib/postgresql/data restart
# Check statuspg_ctl -D /var/lib/postgresql/data status2.10 Initial PostgreSQL Setup
Section titled “2.10 Initial PostgreSQL Setup”Creating Users and Databases
Section titled “Creating Users and Databases”-- Connect to PostgreSQLsudo -u postgres psql
-- Create a new databaseCREATE DATABASE myapp;
-- Create a new user with passwordCREATE USER myuser WITH PASSWORD 'secure_password';
-- Grant privileges on databaseGRANT ALL PRIVILEGES ON DATABASE myapp TO myuser;
-- Make user superuser (optional, not recommended for production)ALTER USER myuser WITH SUPERUSER;
-- Connect to database\c myapp
-- Grant schema privilegesGRANT ALL ON SCHEMA public TO myuser;GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO myuser;GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO myuser;
-- Create role with login capabilityCREATE ROLE app_user WITH LOGIN PASSWORD 'password';CREATE DATABASE app_db;GRANT app_user TO app_db;Setting Up Multiple Environments
Section titled “Setting Up Multiple Environments”-- Create development databaseCREATE DATABASE myapp_dev;GRANT ALL PRIVILEGES ON DATABASE myapp_dev TO developer;
-- Create staging databaseCREATE DATABASE myapp_staging;GRANT ALL PRIVILEGES ON DATABASE myapp_staging TO deploy;
-- Create production databaseCREATE DATABASE myapp_prod;GRANT ALL PRIVILEGES ON DATABASE myapp_prod TO admin;
-- Create read-only role for reportingCREATE ROLE readonly WITH LOGIN PASSWORD 'readonly_password';GRANT CONNECT ON DATABASE myapp_prod TO readonly;GRANT USAGE ON SCHEMA public TO readonly;GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;2.11 Connecting to PostgreSQL
Section titled “2.11 Connecting to PostgreSQL”Using psql
Section titled “Using psql”# Connect to local databasepsql -U postgres
# Connect to specific databasepsql -U postgres -d mydb
# Connect to remote databasepsql -h hostname.example.com -U postgres -d mydb
# Connect with portpsql -h hostname.example.com -p 5433 -U postgres -d mydb
# Using connection stringpsql postgresql://user:password@hostname:5432/mydb
# Execute SQL from command linepsql -U postgres -d mydb -c "SELECT * FROM users LIMIT 5;"
# Execute SQL from filepsql -U postgres -d mydb -f query.sql
# Export query results to CSVpsql -U postgres -d mydb -c "COPY (SELECT * FROM users) TO STDOUT WITH CSV" > output.csv
# Import CSVpsql -U postgres -d mydb -c "COPY users FROM STDIN WITH CSV" < input.csv
# Common psql commands\list or \l -- List databases\dt -- List tables\du -- List users\di -- List indexes\dv -- List views\ds -- List sequences\dn -- List schemas\c dbname -- Connect to database\i file.sql -- Execute SQL file\h -- Help on SQL commands\x -- Expanded display\timing -- Show query timingUsing Connection String (URI Format)
Section titled “Using Connection String (URI Format)”# Standard connection string formatpostgresql://[user[:password]@][host[:port]][/database][?param1=value1&...]
# Examplespsql postgresql://postgres:password@localhost:5432/mydbpsql postgresql://user@localhost/mydbpsql postgresql://user@localhost:5433/mydbpsql postgresql://user@/mydb # Unix socketpsql postgresql://user:@localhost/mydb # No password (prompt)
# With SSLpsql "postgresql://user:password@hostname:5432/mydb?sslmode=require"2.12 Verifying Installation
Section titled “2.12 Verifying Installation”Health Check Commands
Section titled “Health Check Commands”-- Check PostgreSQL versionSELECT version();
-- Check current database sizeSELECT pg_database_size(current_database());
-- List all databases with sizesSELECT datname, pg_size_pretty(pg_database_size(datname)) AS sizeFROM pg_database;
-- Check active connectionsSELECT count(*) FROM pg_stat_activity;
-- Check database uptimeSELECT now() - pg_postmaster_start_time() AS uptime;
-- Check server settingsSHOW all;SHOW max_connections;SHOW shared_buffers;
-- List all tables in current schemaSELECT table_schema, table_nameFROM information_schema.tablesWHERE table_type = 'BASE TABLE';
-- Check table sizesSELECT relname, pg_size_pretty(pg_total_relation_size(relid))FROM pg_catalog.pg_statio_user_tablesORDER BY pg_total_relation_size(relid) DESC;2.13 Best Practices Summary
Section titled “2.13 Best Practices Summary” PostgreSQL Installation Best Practices ========================================================================
1. Choose the Right Version ┌──────────────────────────────────────────────────────────────┐ │ • Use the latest stable version (17.x) │ │ • LTS versions for production stability │ │ • Test thoroughly before upgrading │ └──────────────────────────────────────────────────────────────┘
2. Security Configuration ┌──────────────────────────────────────────────────────────────┐ │ • Change default postgres user password │ │ • Use SCRAM-SHA-256 authentication │ │ • Enable SSL/TLS connections │ │ • Restrict pg_hba.conf access │ │ • Use firewall rules │ └──────────────────────────────────────────────────────────────┘
3. Performance Tuning ┌──────────────────────────────────────────────────────────────┐ │ • Configure shared_buffers appropriately │ │ • Set effective_cache_size │ │ • Tune work_mem for complex queries │ │ • Use SSD storage │ └──────────────────────────────────────────────────────────────┘
4. Backup Configuration ┌──────────────────────────────────────────────────────────────┐ │ • Set up automatic backups │ │ • Configure WAL archiving │ │ • Test restore procedures │ └──────────────────────────────────────────────────────────────┘
5. Monitoring Setup ┌──────────────────────────────────────────────────────────────┐ │ • Enable pg_stat_statements │ │ • Configure logging │ │ • Set up slow query monitoring │ └──────────────────────────────────────────────────────────────┘ ========================================================================Next Chapter
Section titled “Next Chapter”Chapter 3: PostgreSQL Architecture
Last Updated: February 2026