TechLead
Lesson 2 of 22
5 min read
PostgreSQL

Installing PostgreSQL & Basic Setup

Install Postgres locally or with Docker and create your first database

Install PostgreSQL

You can install Postgres directly on your machine, run it via Docker, or use a managed cloud service. Docker is recommended for teams because everyone gets the exact same version and configuration without any OS-level conflicts.

Option 1: Local Install

# macOS (Homebrew)
brew install postgresql@16
brew services start postgresql@16

# Ubuntu/Debian
sudo apt update
sudo apt install postgresql postgresql-contrib
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Windows
# Download the installer from postgresql.org/download/windows

Option 2: Docker

docker run --name postgres   -e POSTGRES_PASSWORD=postgres   -e POSTGRES_DB=app_db   -p 5432:5432   -v pgdata:/var/lib/postgresql/data   -d postgres:16

# Or with docker-compose.yml:
# services:
#   db:
#     image: postgres:16
#     environment:
#       POSTGRES_PASSWORD: postgres
#     ports:
#       - "5432:5432"
#     volumes:
#       - pgdata:/var/lib/postgresql/data

Create a Database and User

After installing, connect as the default superuser and create a dedicated user and database for your application. Never use the superuser for application connections.

-- Connect to the default postgres database
-- (on macOS/Linux: psql postgres  |  on Docker: docker exec -it postgres psql -U postgres)

-- Create an application user with a strong password
CREATE USER app_user WITH PASSWORD 'use-a-strong-password-here';

-- Create the application database, owned by that user
CREATE DATABASE app_db OWNER app_user;

-- Grant all privileges (ownership usually covers this, but it's explicit)
GRANT ALL PRIVILEGES ON DATABASE app_db TO app_user;

-- Verify the setup
l          -- list all databases
du         -- list all users and their roles

Connection Strings

Most libraries, ORMs, and tools accept a standard Postgres URL. Keep this in an environment variable — never commit credentials to source control.

# .env (add to .gitignore)
DATABASE_URL=postgresql://app_user:your-password@localhost:5432/app_db

# With SSL for production
DATABASE_URL=postgresql://app_user:your-password@db.example.com:5432/app_db?sslmode=require

Verifying the Installation

# Check the Postgres version
psql -U app_user -d app_db -c "SELECT version();"

# Quick connectivity test (should return 1)
psql -U app_user -d app_db -c "SELECT 1;"

Common Setup Pitfalls

  • • On macOS, brew services start postgresql@16 may differ from brew services start postgresql — check with brew list | grep postgres.
  • • Docker volumes (-v pgdata:/var/lib/postgresql/data) persist data between container restarts. Without a volume, data is lost when the container stops.
  • • Production databases should always use SSL. Set sslmode=require in your connection string.

Continue Learning