404 Not Found

404 Not Found


nginx

How to Install PostgreSQL and Make Your First Connection

Installing PostgreSQL and making your first connection is the first step in learning it—this article gets a working PG instance running in the fastest way possible.

1. What You'll Learn


2. A New Hire's Real Story

(1) The Pain: Get the Database Running in 30 Minutes

Bob just joined an e-commerce company. His manager asked him to set up a local PostgreSQL dev database within 30 minutes. Bob had only used MySQL before and was completely new to PG:

(2) Docker + DBeaver to the Rescue

Installing PostgreSQL with Docker is the fastest way—one command, no system-specific hassle:

BASH
# Pull and run PostgreSQL 17 in Docker
docker run --name my-postgres \
  -e POSTGRES_PASSWORD=mysecretpassword \
  -e POSTGRES_USER=bob \
  -e POSTGRES_DB=dev_shop \
  -p 5432:5432 \
  -d postgres:17

# Verify the container is running
docker ps | grep my-postgres

(3) The Payoff


3. Installation Methods Compared

Method Pros Cons Best for
Docker Fast, clean, reproducible, one-command teardown Requires Docker first Dev environments (recommended)
Windows installer GUI install, auto-registers as a system service Untidy uninstall, hard version management Windows developers
macOS Homebrew CLI install, easy version switching Requires Homebrew familiarity macOS developers
Linux package manager Native integration, best performance Different commands per distro Linux servers / dev
Cloud service Zero ops, automatic backups Costs money, network latency Production
100%
graph TB
    START[Choose installation method] --> Q1{Need production<br/>performance?}
    Q1 -->|Yes| NAT[Native install<br/>Linux package manager]
    Q1 -->|No| Q2{Already have<br/>Docker?}
    Q2 -->|Yes| DOCKER[Docker install<br/>2 minutes]
    Q2 -->|No| Q3{Your OS?}
    Q3 -->|Windows| WIN[Windows installer<br/>EDB download]
    Q3 -->|macOS| BREW[Homebrew install<br/>brew install postgresql@17]
    Q3 -->|Linux| APT[APT/YUM install<br/>postgresql-17]

(1) Installation Steps

▶ Example: Docker Install of PostgreSQL 17

BASH
# Step 1: Pull PostgreSQL 17 image
docker pull postgres:17

# Step 2: Run container with custom settings
docker run --name pg-dev \
  -e POSTGRES_USER=devuser \
  -e POSTGRES_PASSWORD=devpass123 \
  -e POSTGRES_DB=shopdb \
  -p 5432:5432 \
  -v pgdata:/var/lib/postgresql/data \
  -d postgres:17

# Step 3: Verify container is running
docker ps

# Step 4: Connect via psql inside container
docker exec -it pg-dev psql -U devuser -d shopdb

Output:

TEXT
psql (17.0)
Type "help" for help.

shopdb=>

(2) Common Docker Management Commands

Action Command
Start container docker start pg-dev
Stop container docker stop pg-dev
Restart container docker restart pg-dev
Remove container docker rm -f pg-dev
View logs docker logs pg-dev
Enter psql docker exec -it pg-dev psql -U devuser -d shopdb
💡 Tip: -v pgdata:/var/lib/postgresql/data persists data to a Docker volume, so data survives even after the container is removed.


5. Native Install

(1) Windows Install

▶ Example: Windows Installation Steps

TEXT
1. Download installer from https://www.enterprisedb.com/downloads/postgres
2. Run postgresql-17-windows-x64.exe
3. Select installation directory (default: C:\Program Files\PostgreSQL\17)
4. Set superuser (postgres) password
5. Set port (default: 5432)
6. Select locale (default: [Default locale])
7. Check "Launch Stack Builder at exit" (optional, for additional tools)
8. Click Finish

After installation, PostgreSQL automatically registers and starts as a Windows service.

(2) macOS Homebrew Install

▶ Example: macOS Installation Steps

BASH
# Install PostgreSQL 17 via Homebrew
brew install postgresql@17

# Start PostgreSQL service
brew services start postgresql@17

# Connect to default database
psql postgres

# Verify version
SELECT version();

Output:

TEXT
# psql command executed successfully

(3) Linux Install

▶ Example: Ubuntu/Debian Installation Steps

BASH
# Add PostgreSQL official APT repository
sudo apt update
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

sudo sh -c '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" \
  > /etc/apt/sources.list.d/pgdg.list'

# Install PostgreSQL 17
sudo apt update
sudo apt install -y postgresql-17

# Switch to postgres user and connect
sudo -u postgres psql

# Verify installation
SELECT version();

Output:

TEXT
# psql command executed successfully
Distro Install command Service management
Ubuntu/Debian sudo apt install postgresql-17 sudo systemctl start/stop/restart postgresql
RHEL/CentOS sudo dnf install postgresql-server sudo systemctl start/stop/restart postgresql
Arch Linux sudo pacman -S postgresql sudo systemctl start/stop/restart postgresql

6. GUI Management Tools

(1) pgAdmin 4 vs DBeaver

Dimension pgAdmin 4 DBeaver
Positioning Official PostgreSQL admin tool Universal database admin tool
Databases supported PostgreSQL only PostgreSQL + MySQL + SQLite + Oracle, 20+ total
Cost Free Community free / Enterprise paid
Platform Web browser + desktop Windows / macOS / Linux desktop
PG feature support Best (native support for all PG features) Good (common features supported)
Recommended for PG-specific projects, PG-unique features Multi-DB environments, daily dev/debug
💡 Tip: Install both—use pgAdmin for PG-specific operations (e.g., viewing execution plans, managing extensions) and DBeaver for daily SQL development and data browsing.

(2) pgAdmin 4 Install

▶ Example: Connect to Database with pgAdmin 4

TEXT
1. Download from https://www.pgadmin.org/download/
2. Install and launch pgAdmin 4
3. Click "Add New Server"
4. General tab: Name = "Local Dev"
5. Connection tab:
   - Host: localhost (or 127.0.0.1)
   - Port: 5432
   - Maintenance database: shopdb
   - Username: devuser
   - Password: devpass123
6. Click Save

(3) DBeaver Install

▶ Example: Connect PostgreSQL with DBeaver

TEXT
1. Download from https://dbeaver.io/download/ (Community Edition)
2. Install and launch DBeaver
3. Click "New Database Connection" (plug icon)
4. Select PostgreSQL
5. Fill connection settings:
   - Host: localhost
   - Port: 5432
   - Database: shopdb
   - Username: devuser
   - Password: devpass123
6. Click "Test Connection" (prompts to download the PG JDBC driver)
7. Click Finish

7. psql Command-Line Connection

psql is PostgreSQL's built-in command-line client and the most common interactive tool.

(1) Connection Parameters

Parameter Short Default Description
--host -h localhost Database server address
--port -p 5432 Port number
--username -U Current OS user Connection username
--dbname -d Same as username Database name to connect to
--password -W none Force password prompt

▶ Example: Connect with psql

BASH
# Connect to local PostgreSQL
psql -h localhost -p 5432 -U devuser -d shopdb

# Or use a connection URI
psql "postgresql://devuser:devpass123@localhost:5432/shopdb"

# Or via Docker
docker exec -it pg-dev psql -U devuser -d shopdb

Output:

TEXT
CONTAINER ID   IMAGE     STATUS    
abc123         latest    Up 2 hours

(2) Common psql Meta-Commands

psql meta-commands start with \ and need no semicolon:

Command Function Example
\l List all databases \l
\c dbname Switch database \c shopdb
\dt List tables in current database \dt
\d tablename Show table structure \d users
\du List all users/roles \du
\df List all functions \df
\dx List installed extensions \dx
\conninfo Show current connection info \conninfo
\q Quit psql \q
\? Help (all meta-commands) \?

▶ Example: Basic psql Operations

SQL
-- Check connection info
\conninfo

-- List databases
\l

-- Create a test table
CREATE TABLE test_greeting (
    id SERIAL PRIMARY KEY,
    message TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Insert data
INSERT INTO test_greeting (message) VALUES ('Hello, PostgreSQL!');

-- Query data
SELECT * FROM test_greeting;

-- Drop test table
DROP TABLE test_greeting;

Output:

TEXT
-- \conninfo output:
You are connected to database "shopdb" as user "devuser" on host "localhost" at port "5432".

-- SELECT output:
 id |      message       |         created_at
----+--------------------+----------------------------
  1 | Hello, PostgreSQL! | 2026-07-13 10:30:00.123456

8. Starting and Stopping the Service

Environment Start Stop Restart Status
Docker docker start pg-dev docker stop pg-dev docker restart pg-dev docker ps
Linux (systemd) sudo systemctl start postgresql sudo systemctl stop postgresql sudo systemctl restart postgresql sudo systemctl status postgresql
macOS (Homebrew) brew services start postgresql@17 brew services stop postgresql@17 brew services restart postgresql@17 brew services list
Windows Service auto-starts net stop postgresql-x64-17 net stop then net start Check Services manager

9. Complete Example: From Install to Verify

BASH
# ============================================
# Complete workflow: install, connect, verify
# From zero to running in 5 commands
# ============================================

# 1. Start PostgreSQL via Docker
docker run --name pg-dev \
  -e POSTGRES_USER=devuser \
  -e POSTGRES_PASSWORD=devpass123 \
  -e POSTGRES_DB=shopdb \
  -p 5432:5432 \
  -d postgres:17

# 2. Wait for container to be ready (about 5 seconds)
sleep 5

# 3. Connect via psql
docker exec -it pg-dev psql -U devuser -d shopdb

# 4. Inside psql: run verification queries
# (Type these commands in the psql prompt)

-- Show PostgreSQL version
SELECT version();

-- Show current connection
\conninfo

-- List available extensions
SELECT name, default_version FROM pg_available_extensions LIMIT 5;

-- Create a test table and insert data
CREATE TABLE hello_pg (
    id SERIAL PRIMARY KEY,
    greeting TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

INSERT INTO hello_pg (greeting) VALUES
    ('Hello from PostgreSQL!'),
    ('Docker install works!'),
    ('Ready to learn!');

-- Verify
SELECT * FROM hello_pg;

-- Clean up
DROP TABLE hello_pg;

-- Exit psql
\q

# 5. Stop container when done
docker stop pg-dev

Output (excerpt):

TEXT
                                                     version
-----------------------------------------------------------------------------------------------------------------
 PostgreSQL 17.0 on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit

     name      | default_version
---------------+-----------------
 plpgsql       | 1.0
 uuid-ossp     | 1.1
 pg_trgm       | 1.6

 id |       greeting        |          created_at
----+-----------------------+-------------------------------
  1 | Hello from PostgreSQL! | 2026-07-13 10:30:00+00
  2 | Docker install works!  | 2026-07-13 10:30:00+00
  3 | Ready to learn!        | 2026-07-13 10:30:00+00

❓ FAQ

Q What's the difference between Docker-installed and natively-installed PostgreSQL?
A Functionally identical. The only difference is how it runs: Docker is isolated in a container, native runs directly on the OS. For dev, Docker is recommended (clean, reproducible); for production, native is recommended (best performance, no Docker overhead).
Q How do I confirm PostgreSQL is running after install?
A The simplest way is psql -U postgres -c "SELECT 1". If it returns 1, PG is running and reachable. In Docker, check container status with docker ps | grep postgres.
Q I forgot the postgres user password—what now?
A Temporarily change the auth method in pg_hba.conf to trust (no password), restart PG, then reset with ALTER USER postgres PASSWORD 'new_password', and switch the auth back to md5 or scram-sha-256.
Q Port 5432 is occupied—what do I do?
A Use lsof -i :5432 (macOS/Linux) or netstat -ano | findstr 5432 (Windows) to find the process using it. You can either stop that process or change PG's port (set port = 5433 in postgresql.conf).
Q pgAdmin opens very slowly—what do I do?
A pgAdmin 4 is a web app; the first launch loads a browser engine and may take 10–30 seconds. If it stays slow, try Desktop mode or switch to DBeaver (faster startup).
Q Why recommend DBeaver instead of only pgAdmin?
A DBeaver starts faster, supports multiple databases, and has a smarter SQL editor (autocomplete / formatting). pgAdmin's strength is more complete PG-feature support (e.g., pgAgent scheduled jobs, ER-diagram tool). Using both is best.

📖 Summary


📝 Exercises

  1. Basic (★): Install PostgreSQL 17 with Docker, connect via psql, run SELECT version();, and record the output.

  2. Intermediate (★★): Install DBeaver and create a connection to your local PostgreSQL. In DBeaver, create a todo_items table (columns: id, title, completed, created_at), insert 3 test rows, and query them.

  3. Challenge (★★★): Install both pgAdmin 4 and DBeaver and connect to the same PostgreSQL instance. In each tool, view the pg_available_extensions system catalog and compare how the two display it. Write which tool you prefer for this kind of system data and why.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏