How do you set up PostgreSQL and log in with psql?

BeginnerHands-onPostgreSQL
Answer

Short answer

Run PostgreSQL in Docker with a password (or install it with apt), then log in with the psql client: psql -U postgres locally, or psql -h <host> -U <user> -d <database> remotely. The default port is 5432.

Option 1 — Docker

docker run -d --name postgres \
  -e POSTGRES_PASSWORD='Pg@12345' \
  -e POSTGRES_DB=shop \
  -p 5432:5432 \
  -v pg-data:/var/lib/postgresql/data \
  postgres:16

docker exec -it postgres psql -U postgres -d shop

Option 2 — Install on Ubuntu

sudo apt update && sudo apt install -y postgresql
sudo systemctl enable --now postgresql
sudo -u postgres psql            # log in as the postgres system user

Logging in remotely

psql -h db.internal -p 5432 -U app_user -d shop
# or one URL
psql "postgresql://app_user:[email protected]:5432/shop?sslmode=require"

psql commands you must know

These start with a backslash and are psql shortcuts, not SQL:

Command What it does
\l List databases
\c shop Connect (switch) to database shop
\dt List tables
\d customers Describe a table: columns, types, indexes
\du List users (roles)
\x Toggle expanded output (easier to read wide rows)
\q Quit

What to say in the interview

"I run PostgreSQL in Docker with POSTGRES_PASSWORD and a volume, or install it with apt and manage it with systemctl. I connect with psql — -h for host, -U for user, -d for database. Inside psql I use \l to list databases, \c to switch, \dt to list tables and \d to describe one. On AWS it's usually RDS or Aurora PostgreSQL, and connections typically need sslmode=require."

Follow-up questions you may get

  • Where are connection rules configured? pg_hba.conf controls who can connect from where; postgresql.conf holds settings like listen_addresses.
  • Why does a remote login fail with "no pg_hba.conf entry"? The server doesn't allow that user from that IP — add a rule to pg_hba.conf and reload.
All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: PostgreSQL basics

More on PostgreSQL